mirror of
https://github.com/XTLS/Xray-core.git
synced 2026-12-05 08:04:13 +00:00
Compare commits
2
Commits
panic
..
findprocess
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
953097e9dc | ||
|
|
73a3beff39 |
@@ -7,6 +7,7 @@ import (
|
|||||||
"github.com/xtls/xray-core/app/proxyman"
|
"github.com/xtls/xray-core/app/proxyman"
|
||||||
"github.com/xtls/xray-core/common"
|
"github.com/xtls/xray-core/common"
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"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/serial"
|
||||||
"github.com/xtls/xray-core/common/session"
|
"github.com/xtls/xray-core/common/session"
|
||||||
"github.com/xtls/xray-core/core"
|
"github.com/xtls/xray-core/core"
|
||||||
@@ -183,6 +184,9 @@ func NewHandler(ctx context.Context, config *core.InboundHandlerConfig) (inbound
|
|||||||
Mark: streamSettings.SocketSettings.Mark,
|
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)
|
return NewAlwaysOnInboundHandler(ctx, tag, receiverSettings, proxySettings)
|
||||||
}
|
}
|
||||||
|
|||||||
+23
-3
@@ -15,6 +15,8 @@ const (
|
|||||||
|
|
||||||
var ErrBufferFull = errors.New("buffer is full")
|
var ErrBufferFull = errors.New("buffer is full")
|
||||||
|
|
||||||
|
var pool = bytespool.GetPool(Size)
|
||||||
|
|
||||||
// ownership represents the data owner of the buffer.
|
// ownership represents the data owner of the buffer.
|
||||||
type ownership uint8
|
type ownership uint8
|
||||||
|
|
||||||
@@ -37,7 +39,16 @@ type Buffer struct {
|
|||||||
|
|
||||||
// New creates a Buffer with 0 length and 8K capacity, managed.
|
// New creates a Buffer with 0 length and 8K capacity, managed.
|
||||||
func New() *Buffer {
|
func New() *Buffer {
|
||||||
return &Buffer{v: bytespool.Alloc(Size)}
|
buf := pool.Get().([]byte)
|
||||||
|
if cap(buf) >= Size {
|
||||||
|
buf = buf[:Size]
|
||||||
|
} else {
|
||||||
|
buf = make([]byte, Size)
|
||||||
|
}
|
||||||
|
|
||||||
|
return &Buffer{
|
||||||
|
v: buf,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewExisted creates a standard size Buffer with an existed bytearray, managed.
|
// NewExisted creates a standard size Buffer with an existed bytearray, managed.
|
||||||
@@ -69,7 +80,16 @@ func FromBytes(b []byte) *Buffer {
|
|||||||
// StackNew creates a new Buffer object on stack, managed.
|
// StackNew creates a new Buffer object on stack, managed.
|
||||||
// This method is for buffers that is released in the same function.
|
// This method is for buffers that is released in the same function.
|
||||||
func StackNew() Buffer {
|
func StackNew() Buffer {
|
||||||
return Buffer{v: bytespool.Alloc(Size)}
|
buf := pool.Get().([]byte)
|
||||||
|
if cap(buf) >= Size {
|
||||||
|
buf = buf[:Size]
|
||||||
|
} else {
|
||||||
|
buf = make([]byte, Size)
|
||||||
|
}
|
||||||
|
|
||||||
|
return Buffer{
|
||||||
|
v: buf,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
|
// NewWithSize creates a Buffer with 0 length and capacity with at least the given size, bytespool's.
|
||||||
@@ -93,7 +113,7 @@ func (b *Buffer) Release() {
|
|||||||
switch b.ownership {
|
switch b.ownership {
|
||||||
case managed:
|
case managed:
|
||||||
if cap(p) == Size {
|
if cap(p) == Size {
|
||||||
bytespool.Free(p)
|
pool.Put(p)
|
||||||
}
|
}
|
||||||
case bytespools:
|
case bytespools:
|
||||||
bytespool.Free(p)
|
bytespool.Free(p)
|
||||||
|
|||||||
+55
-67
@@ -1,84 +1,72 @@
|
|||||||
package bytespool
|
package bytespool
|
||||||
|
|
||||||
import (
|
import "sync"
|
||||||
"math/bits"
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
func createAllocFunc(size int32) func() interface{} {
|
||||||
minShift = 10 // 1KB
|
return func() interface{} {
|
||||||
maxShift = 16 // 64KB
|
return make([]byte, size)
|
||||||
numPools = maxShift - minShift + 1
|
}
|
||||||
minSize = 1 << minShift
|
|
||||||
maxSize = 1 << maxShift
|
|
||||||
)
|
|
||||||
|
|
||||||
// pools hold array pointers (*[N]byte) to avoid interface boxing allocations on Put.
|
|
||||||
var pools = [numPools]sync.Pool{
|
|
||||||
{New: func() any { return new([1 << 10]byte) }},
|
|
||||||
{New: func() any { return new([1 << 11]byte) }},
|
|
||||||
{New: func() any { return new([1 << 12]byte) }},
|
|
||||||
{New: func() any { return new([1 << 13]byte) }},
|
|
||||||
{New: func() any { return new([1 << 14]byte) }},
|
|
||||||
{New: func() any { return new([1 << 15]byte) }},
|
|
||||||
{New: func() any { return new([1 << 16]byte) }},
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 1024.
|
// The following parameters controls the size of buffer pools.
|
||||||
|
// There are numPools pools. Starting from 2k size, the size of each pool is sizeMulti of the previous one.
|
||||||
|
// Package buf is guaranteed to not use buffers larger than the largest pool.
|
||||||
|
// Other packets may use larger buffers.
|
||||||
|
const (
|
||||||
|
numPools = 4
|
||||||
|
sizeMulti = 4
|
||||||
|
)
|
||||||
|
|
||||||
|
var (
|
||||||
|
pool [numPools]sync.Pool
|
||||||
|
poolSize [numPools]int32
|
||||||
|
)
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
size := int32(2048)
|
||||||
|
for i := 0; i < numPools; i++ {
|
||||||
|
pool[i] = sync.Pool{
|
||||||
|
New: createAllocFunc(size),
|
||||||
|
}
|
||||||
|
poolSize[i] = size
|
||||||
|
size *= sizeMulti
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// GetPool returns a sync.Pool that generates bytes array with at least the given size.
|
||||||
|
// It may return nil if no such pool exists.
|
||||||
|
//
|
||||||
|
// xray:api:stable
|
||||||
|
func GetPool(size int32) *sync.Pool {
|
||||||
|
for idx, ps := range poolSize {
|
||||||
|
if size <= ps {
|
||||||
|
return &pool[idx]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Alloc returns a byte slice with at least the given size. Minimum size of returned slice is 2048.
|
||||||
//
|
//
|
||||||
// xray:api:stable
|
// xray:api:stable
|
||||||
func Alloc(size int32) []byte {
|
func Alloc(size int32) []byte {
|
||||||
if size > maxSize {
|
pool := GetPool(size)
|
||||||
return make([]byte, size)
|
if pool != nil {
|
||||||
}
|
return pool.Get().([]byte)
|
||||||
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.
|
// Free puts a byte slice into the internal pool.
|
||||||
//
|
//
|
||||||
// xray:api:stable
|
// xray:api:stable
|
||||||
func Free(b []byte) {
|
func Free(b []byte) {
|
||||||
c := cap(b)
|
size := int32(cap(b))
|
||||||
if c < minSize || c > maxSize {
|
b = b[0:cap(b)]
|
||||||
return
|
for i := numPools - 1; i >= 0; i-- {
|
||||||
}
|
if size >= poolSize[i] {
|
||||||
index := bits.Len(uint(c)) - 1 - minShift
|
pool[i].Put(b)
|
||||||
switch index {
|
return
|
||||||
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]))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,15 +3,19 @@
|
|||||||
package net
|
package net
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"slices"
|
"path/filepath"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
|
"github.com/vishvananda/netlink/nl"
|
||||||
|
"golang.org/x/sys/unix"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/bytespool"
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -27,50 +31,20 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
|
|||||||
panic("Unsupported network type for process lookup.")
|
panic("Unsupported network type for process lookup.")
|
||||||
}
|
}
|
||||||
|
|
||||||
var procFiles []string
|
socket, err := findSocketInode(network, net.ParseIP(srcIP), srcPort)
|
||||||
|
|
||||||
switch network {
|
|
||||||
case "tcp":
|
|
||||||
if net.ParseIP(srcIP).To4() != nil {
|
|
||||||
procFiles = []string{"/proc/net/tcp", "/proc/net/tcp6"}
|
|
||||||
} else {
|
|
||||||
procFiles = []string{"/proc/net/tcp6"}
|
|
||||||
}
|
|
||||||
case "udp":
|
|
||||||
if net.ParseIP(srcIP).To4() != nil {
|
|
||||||
procFiles = []string{"/proc/net/udp", "/proc/net/udp6"}
|
|
||||||
} else {
|
|
||||||
procFiles = []string{"/proc/net/udp6", "/proc/net/udp"}
|
|
||||||
}
|
|
||||||
default:
|
|
||||||
panic("Unsupported network type for process lookup.")
|
|
||||||
}
|
|
||||||
|
|
||||||
targetHexAddrs := []string{formatProcNetAddress(net.ParseIP(srcIP).To16(), Port(srcPort))}
|
|
||||||
if ipv4 := net.ParseIP(srcIP).To4(); ipv4 != nil {
|
|
||||||
// the one above is then the IPv4-mapped IPv6 address that an IPv6 socket has it as, in the IPv6 file
|
|
||||||
targetHexAddrs = append(targetHexAddrs, formatProcNetAddress(ipv4, Port(srcPort)))
|
|
||||||
}
|
|
||||||
|
|
||||||
portFallback := ""
|
|
||||||
if network == "udp" {
|
|
||||||
portFallback = fmt.Sprintf(":%04X", srcPort)
|
|
||||||
}
|
|
||||||
|
|
||||||
inode, err := findInodeInFiles(procFiles, targetHexAddrs, portFallback)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, "", "", errors.New("could not search in ", strings.Join(procFiles, " and ")).Base(err)
|
return 0, "", "", errors.New("could not query sockets using netlink").Base(err)
|
||||||
}
|
}
|
||||||
if inode == "" {
|
if socket == nil {
|
||||||
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found in ", strings.Join(procFiles, " or "))
|
return 0, "", "", errors.New("connection for ", srcIP, ":", srcPort, " not found")
|
||||||
}
|
}
|
||||||
|
|
||||||
pidStr, err := findPidByInode(inode)
|
pidStr, err := findPidByInode(socket.inode, socket.uid)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, "", "", errors.New("could not find PID for inode ", inode, ": ", err)
|
return 0, "", "", errors.New("could not find PID for inode ", socket.inode, ": ", err)
|
||||||
}
|
}
|
||||||
if pidStr == "" {
|
if pidStr == "" {
|
||||||
return 0, "", "", errors.New("no process found for inode ", inode)
|
return 0, "", "", errors.New("no process found for inode ", socket.inode)
|
||||||
}
|
}
|
||||||
|
|
||||||
absPath, err := getAbsPath(pidStr)
|
absPath, err := getAbsPath(pidStr)
|
||||||
@@ -89,59 +63,94 @@ func FindProcess(network, srcIP string, srcPort uint16, destIP string, destPort
|
|||||||
return pid, procName, absPath, nil
|
return pid, procName, absPath, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// formatProcNetAddress formats the 4 or 16 bytes of addr as they are: an IPv4-mapped IPv6 address stays one
|
type processSocket struct {
|
||||||
func formatProcNetAddress(addr net.IP, port Port) string {
|
inode string
|
||||||
ipBytes := []byte(addr)
|
uid uint32
|
||||||
|
|
||||||
var formatted strings.Builder
|
|
||||||
formatted.Grow(len(ipBytes)*2 + 5)
|
|
||||||
for i := 0; i < len(ipBytes); i += 4 {
|
|
||||||
fmt.Fprintf(&formatted, "%08X", binary.NativeEndian.Uint32(ipBytes[i:i+4]))
|
|
||||||
}
|
|
||||||
fmt.Fprintf(&formatted, ":%04X", uint16(port))
|
|
||||||
return formatted.String()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func findInodeInFiles(filePaths []string, targetHexAddrs []string, portFallback string) (string, error) {
|
// Layouts are defined by Linux's inet_diag_req_v2 and inet_diag_msg.
|
||||||
onlyMatchedPort := ""
|
const (
|
||||||
|
inetDiagRequestSize = 56
|
||||||
|
inetDiagResponseSize = 72
|
||||||
|
tcpBoundInactive = 13
|
||||||
|
)
|
||||||
|
|
||||||
for i, filePath := range filePaths {
|
func findSocketInode(network string, ip net.IP, port uint16) (*processSocket, error) {
|
||||||
file, err := os.Open(filePath)
|
families := []uint8{unix.AF_INET6}
|
||||||
|
if ip.To4() != nil {
|
||||||
|
families = []uint8{unix.AF_INET, unix.AF_INET6}
|
||||||
|
} else if network == "udp" {
|
||||||
|
families = append(families, unix.AF_INET)
|
||||||
|
}
|
||||||
|
|
||||||
|
protocol := byte(unix.IPPROTO_UDP)
|
||||||
|
if network == "tcp" {
|
||||||
|
protocol = unix.IPPROTO_TCP
|
||||||
|
}
|
||||||
|
|
||||||
|
var wildcard *processSocket
|
||||||
|
request := make([]byte, inetDiagRequestSize)
|
||||||
|
for _, family := range families {
|
||||||
|
clear(request)
|
||||||
|
request[0], request[1] = family, protocol
|
||||||
|
states := ^uint32(0)
|
||||||
|
if network == "tcp" {
|
||||||
|
states &^= 1 << tcpBoundInactive
|
||||||
|
}
|
||||||
|
binary.NativeEndian.PutUint32(request[4:8], states)
|
||||||
|
binary.BigEndian.PutUint16(request[8:10], port)
|
||||||
|
if family == unix.AF_INET {
|
||||||
|
copy(request[12:28], ip.To4())
|
||||||
|
} else {
|
||||||
|
copy(request[12:28], ip.To16())
|
||||||
|
}
|
||||||
|
binary.NativeEndian.PutUint32(request[48:52], ^uint32(0))
|
||||||
|
binary.NativeEndian.PutUint32(request[52:56], ^uint32(0))
|
||||||
|
|
||||||
|
req := nl.NewNetlinkRequest(nl.SOCK_DIAG_BY_FAMILY, unix.NLM_F_DUMP)
|
||||||
|
req.AddRawData(request)
|
||||||
|
var exact *processSocket
|
||||||
|
var parseErr error
|
||||||
|
err := req.ExecuteIter(unix.NETLINK_INET_DIAG, nl.SOCK_DIAG_BY_FAMILY, func(msg []byte) bool {
|
||||||
|
if len(msg) < inetDiagResponseSize {
|
||||||
|
parseErr = fmt.Errorf("short inet_diag response: %d bytes", len(msg))
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if msg[0] != family || binary.BigEndian.Uint16(msg[4:6]) != port {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
source := net.IP(msg[8:24])
|
||||||
|
if family == unix.AF_INET {
|
||||||
|
source = source[:4]
|
||||||
|
}
|
||||||
|
if !source.Equal(ip) && !(network == "udp" && source.IsUnspecified()) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
socket := &processSocket{
|
||||||
|
uid: binary.NativeEndian.Uint32(msg[64:68]),
|
||||||
|
inode: strconv.FormatUint(uint64(binary.NativeEndian.Uint32(msg[68:72])), 10),
|
||||||
|
}
|
||||||
|
if source.Equal(ip) {
|
||||||
|
exact = socket
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
wildcard = socket
|
||||||
|
return true
|
||||||
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
if i > 0 && os.IsNotExist(err) {
|
return nil, err
|
||||||
continue
|
|
||||||
}
|
|
||||||
return "", err
|
|
||||||
}
|
}
|
||||||
defer file.Close()
|
if parseErr != nil {
|
||||||
|
return nil, parseErr
|
||||||
scanner := bufio.NewScanner(file)
|
|
||||||
for scanner.Scan() {
|
|
||||||
fields := strings.Fields(scanner.Text())
|
|
||||||
if len(fields) < 10 {
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
|
|
||||||
localAddress := fields[1]
|
|
||||||
if slices.Contains(targetHexAddrs, localAddress) {
|
|
||||||
return fields[9], nil
|
|
||||||
}
|
|
||||||
if portFallback != "" && strings.HasSuffix(localAddress, portFallback) {
|
|
||||||
wildcardIP := strings.TrimSuffix(localAddress, portFallback)
|
|
||||||
if (len(wildcardIP) == 8 || len(wildcardIP) == 32) && strings.Trim(wildcardIP, "0") == "" {
|
|
||||||
onlyMatchedPort = fields[9]
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if err := scanner.Err(); err != nil {
|
if exact != nil {
|
||||||
return "", err
|
return exact, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return wildcard, nil
|
||||||
return onlyMatchedPort, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func findPidByInode(inode string) (string, error) {
|
func findPidByInode(inode string, uid uint32) (string, error) {
|
||||||
procDir, err := os.ReadDir("/proc")
|
procDir, err := os.ReadDir("/proc")
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return "", err
|
return "", err
|
||||||
@@ -158,26 +167,45 @@ func findPidByInode(inode string) (string, error) {
|
|||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
fdPath := fmt.Sprintf("/proc/%s/fd", pid)
|
info, err := entry.Info()
|
||||||
fdDir, err := os.ReadDir(fdPath)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
stat, ok := info.Sys().(*syscall.Stat_t)
|
||||||
for _, fdEntry := range fdDir {
|
if !ok {
|
||||||
linkPath := fmt.Sprintf("%s/%s", fdPath, fdEntry.Name())
|
return "", fmt.Errorf("unexpected stat data for process %s", pid)
|
||||||
linkTarget, err := os.Readlink(linkPath)
|
}
|
||||||
if err != nil {
|
if stat.Uid != uid {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if linkTarget == targetLink {
|
if processHasSocket(pid, targetLink) {
|
||||||
return pid, nil
|
return pid, nil
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "", nil
|
return "", nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func processHasSocket(pid, targetLink string) bool {
|
||||||
|
fdPath := filepath.Join("/proc", pid, "fd")
|
||||||
|
fdDir, err := os.ReadDir(fdPath)
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer := bytespool.Alloc(unix.PathMax)
|
||||||
|
defer bytespool.Free(buffer)
|
||||||
|
for _, fdEntry := range fdDir {
|
||||||
|
n, err := unix.Readlink(filepath.Join(fdPath, fdEntry.Name()), buffer)
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if string(buffer[:n]) == targetLink {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func getAbsPath(pid string) (string, error) {
|
func getAbsPath(pid string) (string, error) {
|
||||||
path := fmt.Sprintf("/proc/%s/exe", pid)
|
path := fmt.Sprintf("/proc/%s/exe", pid)
|
||||||
return os.Readlink(path)
|
return os.Readlink(path)
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package protocol
|
package protocol
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/xtls/xray-core/common/errors"
|
|
||||||
"github.com/xtls/xray-core/common/net"
|
"github.com/xtls/xray-core/common/net"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -18,9 +17,6 @@ func NewServerSpec(dest net.Destination, user *MemoryUser) *ServerSpec {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func NewServerSpecFromPB(spec *ServerEndpoint) (*ServerSpec, error) {
|
func NewServerSpecFromPB(spec *ServerEndpoint) (*ServerSpec, error) {
|
||||||
if spec == nil || spec.Address == nil {
|
|
||||||
return nil, errors.New("server address is not set")
|
|
||||||
}
|
|
||||||
dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port))
|
dest := net.TCPDestination(spec.Address.AsAddress(), net.Port(spec.Port))
|
||||||
var dUser *MemoryUser
|
var dUser *MemoryUser
|
||||||
if spec.User != nil {
|
if spec.User != nil {
|
||||||
|
|||||||
@@ -191,10 +191,18 @@ func getConfig() string {
|
|||||||
{
|
{
|
||||||
"protocol": "vless",
|
"protocol": "vless",
|
||||||
"settings": {
|
"settings": {
|
||||||
"address": "1.2.3.4",
|
"vnext": [
|
||||||
"port": 1234,
|
{
|
||||||
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
|
"address": "1.2.3.4",
|
||||||
"encryption": "none"
|
"port": 1234,
|
||||||
|
"users": [
|
||||||
|
{
|
||||||
|
"id": "4784f9b8-a879-4fec-9718-ebddefa47750",
|
||||||
|
"encryption": "none"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
]
|
||||||
},
|
},
|
||||||
"tag": "XHTTP_IN",
|
"tag": "XHTTP_IN",
|
||||||
"streamSettings": {
|
"streamSettings": {
|
||||||
|
|||||||
@@ -71,6 +71,7 @@ func (t *ActivityTimer) SetTimeout(timeout time.Duration) {
|
|||||||
}
|
}
|
||||||
common.CloseIfExists(t.checkTask)
|
common.CloseIfExists(t.checkTask)
|
||||||
t.checkTask = newCheckTask
|
t.checkTask = newCheckTask
|
||||||
|
t.Update()
|
||||||
common.Must(newCheckTask.Start())
|
common.Must(newCheckTask.Start())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -58,11 +58,15 @@ func (t *Periodic) Start() error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
t.running = true
|
t.running = true
|
||||||
t.timer = time.AfterFunc(t.Interval, func() {
|
|
||||||
t.checkedExecute()
|
|
||||||
})
|
|
||||||
t.access.Unlock()
|
t.access.Unlock()
|
||||||
|
|
||||||
|
if err := t.checkedExecute(); err != nil {
|
||||||
|
t.access.Lock()
|
||||||
|
t.running = false
|
||||||
|
t.access.Unlock()
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -20,17 +20,17 @@ func TestPeriodicTaskStop(t *testing.T) {
|
|||||||
common.Must(task.Start())
|
common.Must(task.Start())
|
||||||
time.Sleep(time.Second * 5)
|
time.Sleep(time.Second * 5)
|
||||||
common.Must(task.Close())
|
common.Must(task.Close())
|
||||||
if value != 2 {
|
if value != 3 {
|
||||||
t.Fatal("expected 2, but got ", value)
|
t.Fatal("expected 3, but got ", value)
|
||||||
}
|
}
|
||||||
time.Sleep(time.Second * 4)
|
time.Sleep(time.Second * 4)
|
||||||
if value != 2 {
|
if value != 3 {
|
||||||
t.Fatal("expected 2, but got ", value)
|
t.Fatal("expected 3, but got ", value)
|
||||||
}
|
}
|
||||||
common.Must(task.Start())
|
common.Must(task.Start())
|
||||||
time.Sleep(time.Second * 3)
|
time.Sleep(time.Second * 3)
|
||||||
if value != 3 {
|
if value != 5 {
|
||||||
t.Fatal("Expected 3, but ", value)
|
t.Fatal("Expected 5, but ", value)
|
||||||
}
|
}
|
||||||
common.Must(task.Close())
|
common.Must(task.Close())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ module github.com/xtls/xray-core
|
|||||||
go 1.27
|
go 1.27
|
||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a
|
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c
|
||||||
github.com/bufbuild/protocompile v0.14.1
|
github.com/bufbuild/protocompile v0.14.1
|
||||||
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
|
github.com/ghodss/yaml v1.0.1-0.20220118164431-d8423dcdf344
|
||||||
github.com/golang/mock v1.7.0-rc.1
|
github.com/golang/mock v1.7.0-rc.1
|
||||||
@@ -36,7 +36,7 @@ require (
|
|||||||
google.golang.org/protobuf v1.36.12
|
google.golang.org/protobuf v1.36.12
|
||||||
h12.io/socks v1.0.3
|
h12.io/socks v1.0.3
|
||||||
layeh.com/gopher-luar v1.0.11
|
layeh.com/gopher-luar v1.0.11
|
||||||
lukechampine.com/blake3 v1.5.3
|
lukechampine.com/blake3 v1.5.1
|
||||||
mvdan.cc/gofumpt v0.12.0
|
mvdan.cc/gofumpt v0.12.0
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a h1:uCIlOCbXUtBkFk47HxIkQieCkV+zKv5VCDawLtj3Pkc=
|
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c h1:cxK8qTA0YCsj68A7zLYDCfPgMTOyt3ePkHh+oXEmYU0=
|
||||||
github.com/apernet/quic-go v0.65.1-0.20261109005002-2895f039137a/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
|
github.com/apernet/quic-go v0.63.1-0.20261004180939-a10df75c260c/go.mod h1:J7UZVOMF2M1LiE3iiUZWPuy8YCPAcLJOwVURrfJCvc0=
|
||||||
github.com/bufbuild/protocompile v0.14.1 h1:iA73zAf/fyljNjQKwYzUHD6AD4R8KMasmwa/FBatYVw=
|
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/bufbuild/protocompile v0.14.1/go.mod h1:ppVdAIhbr2H8asPk6k4pY7t9zB1OU5DoEw9xY/FUi1c=
|
||||||
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
|
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=
|
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 h1:8zJudpKI6HWkoh9eyyNFaTM79PY6CAPcIr6X/KTiliw=
|
||||||
layeh.com/gopher-luar v1.0.11/go.mod h1:TPnIVCZ2RJBndm7ohXyaqfhzjlZ+OA2SZR/YwL8tECk=
|
layeh.com/gopher-luar v1.0.11/go.mod h1:TPnIVCZ2RJBndm7ohXyaqfhzjlZ+OA2SZR/YwL8tECk=
|
||||||
lukechampine.com/blake3 v1.5.3 h1:q4Ru9Zisjt/knP3KQYuk63VDPnREbSOA6cuL6UwrDlI=
|
lukechampine.com/blake3 v1.5.1 h1:ITRyxe0LlLZcPUWOZ3Taz8mbug/ptn7jbbeeij5ZiPo=
|
||||||
lukechampine.com/blake3 v1.5.3/go.mod h1:+mObCTICmKFFJzAZ+4qqw23+LrWOuO+Zfj3DQiNQFXs=
|
lukechampine.com/blake3 v1.5.1/go.mod h1:QFosUxmjB8mnrWFSNwKmvxHpfY72bmD2tQ0kBMM3kwo=
|
||||||
mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
|
mvdan.cc/gofumpt v0.12.0 h1:1Lbudkz2kpM9Cjz2pL4M19u7q+GaEhCTNf7N9mfpcho=
|
||||||
mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA=
|
mvdan.cc/gofumpt v0.12.0/go.mod h1:SmBHHrljiZu/uoypeKup3rFzP6eoC9UwCp2iH5E3jZA=
|
||||||
|
|||||||
@@ -47,9 +47,6 @@ type Address struct {
|
|||||||
|
|
||||||
// MarshalJSON implements encoding/json.Marshaler.MarshalJSON
|
// MarshalJSON implements encoding/json.Marshaler.MarshalJSON
|
||||||
func (v *Address) MarshalJSON() ([]byte, error) {
|
func (v *Address) MarshalJSON() ([]byte, error) {
|
||||||
if v.Address == nil {
|
|
||||||
return json.Marshal(net.AnyIP.String())
|
|
||||||
}
|
|
||||||
return json.Marshal(v.Address.String())
|
return json.Marshal(v.Address.String())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,9 +68,6 @@ func (v *Address) Build() *net.IPOrDomain {
|
|||||||
if v == nil {
|
if v == nil {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if v.Address == nil {
|
|
||||||
return net.NewIPOrDomain(net.AnyIP)
|
|
||||||
}
|
|
||||||
return net.NewIPOrDomain(v.Address)
|
return net.NewIPOrDomain(v.Address)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+62
-23
@@ -1,6 +1,9 @@
|
|||||||
package conf
|
package conf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/protocol"
|
"github.com/xtls/xray-core/common/protocol"
|
||||||
"github.com/xtls/xray-core/common/serial"
|
"github.com/xtls/xray-core/common/serial"
|
||||||
"github.com/xtls/xray-core/proxy/http"
|
"github.com/xtls/xray-core/proxy/http"
|
||||||
@@ -46,37 +49,73 @@ func (c *HTTPServerConfig) Build() (proto.Message, error) {
|
|||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type HTTPRemoteConfig struct {
|
||||||
|
Address *Address `json:"address"`
|
||||||
|
Port uint16 `json:"port"`
|
||||||
|
Users []json.RawMessage `json:"users"`
|
||||||
|
}
|
||||||
|
|
||||||
type HTTPClientConfig struct {
|
type HTTPClientConfig struct {
|
||||||
Address Address `json:"address"`
|
Address *Address `json:"address"`
|
||||||
Port uint16 `json:"port"`
|
Port uint16 `json:"port"`
|
||||||
Level uint32 `json:"level"`
|
Level uint32 `json:"level"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Username string `json:"user"`
|
Username string `json:"user"`
|
||||||
Password string `json:"pass"`
|
Password string `json:"pass"`
|
||||||
Headers map[string]string `json:"headers"`
|
Servers []*HTTPRemoteConfig `json:"servers"`
|
||||||
|
Headers map[string]string `json:"headers"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *HTTPClientConfig) Build() (proto.Message, error) {
|
func (v *HTTPClientConfig) Build() (proto.Message, error) {
|
||||||
config := new(http.ClientConfig)
|
config := new(http.ClientConfig)
|
||||||
|
if v.Address != nil {
|
||||||
server := &protocol.ServerEndpoint{
|
v.Servers = []*HTTPRemoteConfig{
|
||||||
Address: v.Address.Build(),
|
{
|
||||||
Port: uint32(v.Port),
|
Address: v.Address,
|
||||||
}
|
Port: v.Port,
|
||||||
if len(v.Username) > 0 {
|
},
|
||||||
account := &HTTPAccount{
|
|
||||||
Username: v.Username,
|
|
||||||
Password: v.Password,
|
|
||||||
}
|
}
|
||||||
user := &protocol.User{
|
if len(v.Username) > 0 {
|
||||||
Level: v.Level,
|
v.Servers[0].Users = []json.RawMessage{{}}
|
||||||
Email: v.Email,
|
|
||||||
Account: serial.ToTypedMessage(account.Build()),
|
|
||||||
}
|
}
|
||||||
server.User = user
|
|
||||||
}
|
}
|
||||||
|
if len(v.Servers) != 1 {
|
||||||
config.Server = server
|
return nil, errors.New(`HTTP settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple HTTP outbounds and routing balancer instead`)
|
||||||
|
}
|
||||||
|
for _, serverConfig := range v.Servers {
|
||||||
|
if len(serverConfig.Users) > 1 {
|
||||||
|
return nil, errors.New(`HTTP servers: "users" should have one member at most. Multiple members in "users" should use multiple HTTP outbounds and routing balancer instead`)
|
||||||
|
}
|
||||||
|
server := &protocol.ServerEndpoint{
|
||||||
|
Address: serverConfig.Address.Build(),
|
||||||
|
Port: uint32(serverConfig.Port),
|
||||||
|
}
|
||||||
|
for _, rawUser := range serverConfig.Users {
|
||||||
|
user := new(protocol.User)
|
||||||
|
if v.Address != nil {
|
||||||
|
user.Level = v.Level
|
||||||
|
user.Email = v.Email
|
||||||
|
} else {
|
||||||
|
if err := json.Unmarshal(rawUser, user); err != nil {
|
||||||
|
return nil, errors.New("failed to parse HTTP user").Base(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
account := new(HTTPAccount)
|
||||||
|
if v.Address != nil {
|
||||||
|
account.Username = v.Username
|
||||||
|
account.Password = v.Password
|
||||||
|
} else {
|
||||||
|
if err := json.Unmarshal(rawUser, account); err != nil {
|
||||||
|
return nil, errors.New("failed to parse HTTP account").Base(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
user.Account = serial.ToTypedMessage(account.Build())
|
||||||
|
server.User = user
|
||||||
|
break
|
||||||
|
}
|
||||||
|
config.Server = server
|
||||||
|
break
|
||||||
|
}
|
||||||
config.Header = make([]*http.Header, 0, 32)
|
config.Header = make([]*http.Header, 0, 32)
|
||||||
for key, value := range v.Headers {
|
for key, value := range v.Headers {
|
||||||
config.Header = append(config.Header, &http.Header{
|
config.Header = append(config.Header, &http.Header{
|
||||||
|
|||||||
@@ -11,9 +11,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type HysteriaClientConfig struct {
|
type HysteriaClientConfig struct {
|
||||||
Version int32 `json:"version"`
|
Version int32 `json:"version"`
|
||||||
Address Address `json:"address"`
|
Address *Address `json:"address"`
|
||||||
Port uint16 `json:"port"`
|
Port uint16 `json:"port"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *HysteriaClientConfig) Build() (proto.Message, error) {
|
func (c *HysteriaClientConfig) Build() (proto.Message, error) {
|
||||||
|
|||||||
@@ -12,12 +12,15 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type MasqueClientConfig struct {
|
type MasqueClientConfig struct {
|
||||||
Address Address `json:"address"`
|
Address *Address `json:"address"`
|
||||||
Port uint16 `json:"port"`
|
Port uint16 `json:"port"`
|
||||||
RemoteDNS []string `json:"remoteDNS"`
|
RemoteDNS []string `json:"remoteDNS"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *MasqueClientConfig) Build() (proto.Message, error) {
|
func (c *MasqueClientConfig) Build() (proto.Message, error) {
|
||||||
|
if c.Address == nil {
|
||||||
|
return nil, errors.New(`MASQUE: "address" is not set`)
|
||||||
|
}
|
||||||
if c.Port == 0 {
|
if c.Port == 0 {
|
||||||
return nil, errors.New(`MASQUE: "port" is not set`)
|
return nil, errors.New(`MASQUE: "port" is not set`)
|
||||||
}
|
}
|
||||||
|
|||||||
+55
-26
@@ -177,49 +177,78 @@ func buildShadowsocks2022(v *ShadowsocksServerConfig) (proto.Message, error) {
|
|||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type ShadowsocksServerTarget 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"`
|
||||||
|
}
|
||||||
|
|
||||||
type ShadowsocksClientConfig struct {
|
type ShadowsocksClientConfig struct {
|
||||||
Address Address `json:"address"`
|
Address *Address `json:"address"`
|
||||||
Port uint16 `json:"port"`
|
Port uint16 `json:"port"`
|
||||||
Level byte `json:"level"`
|
Level byte `json:"level"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Cipher string `json:"method"`
|
Cipher string `json:"method"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
|
Servers []*ShadowsocksServerTarget `json:"servers"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
|
func (v *ShadowsocksClientConfig) Build() (proto.Message, error) {
|
||||||
errors.PrintNonRemovalDeprecatedFeatureWarning("Shadowsocks (with no Forward Secrecy, etc.)", "VLESS Encryption")
|
errors.PrintNonRemovalDeprecatedFeatureWarning("Shadowsocks (with no Forward Secrecy, etc.)", "VLESS Encryption")
|
||||||
|
|
||||||
if v.Port == 0 {
|
if v.Address != nil {
|
||||||
|
v.Servers = []*ShadowsocksServerTarget{
|
||||||
|
{
|
||||||
|
Address: v.Address,
|
||||||
|
Port: v.Port,
|
||||||
|
Level: v.Level,
|
||||||
|
Email: v.Email,
|
||||||
|
Cipher: v.Cipher,
|
||||||
|
Password: v.Password,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if len(v.Servers) != 1 {
|
||||||
|
return nil, errors.New(`Shadowsocks settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple Shadowsocks outbounds and routing balancer instead`)
|
||||||
|
}
|
||||||
|
|
||||||
|
server := v.Servers[0]
|
||||||
|
if server.Address == nil {
|
||||||
|
return nil, errors.New("Shadowsocks server address is not set.")
|
||||||
|
}
|
||||||
|
if server.Port == 0 {
|
||||||
return nil, errors.New("Invalid Shadowsocks port.")
|
return nil, errors.New("Invalid Shadowsocks port.")
|
||||||
}
|
}
|
||||||
if v.Password == "" {
|
if server.Password == "" {
|
||||||
return nil, errors.New("Shadowsocks password is not specified.")
|
return nil, errors.New("Shadowsocks password is not specified.")
|
||||||
}
|
}
|
||||||
|
|
||||||
if _, err := shadowsocks_2022.GetCipherMethod(v.Cipher); err == nil {
|
if _, err := shadowsocks_2022.GetCipherMethod(server.Cipher); err == nil {
|
||||||
config := &shadowsocks_2022.ClientConfig{
|
config := new(shadowsocks_2022.ClientConfig)
|
||||||
Address: v.Address.Build(),
|
config.Address = server.Address.Build()
|
||||||
Port: uint32(v.Port),
|
config.Port = uint32(server.Port)
|
||||||
Method: v.Cipher,
|
config.Method = server.Cipher
|
||||||
Key: v.Password,
|
config.Key = server.Password
|
||||||
}
|
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
config := new(shadowsocks.ClientConfig)
|
config := new(shadowsocks.ClientConfig)
|
||||||
if cipherFromString(v.Cipher) == shadowsocks.CipherType_UNKNOWN {
|
account := &shadowsocks.Account{
|
||||||
return nil, errors.New("unknown cipher method: ", v.Cipher)
|
Password: server.Password,
|
||||||
|
}
|
||||||
|
account.CipherType = cipherFromString(server.Cipher)
|
||||||
|
if account.CipherType == shadowsocks.CipherType_UNKNOWN {
|
||||||
|
return nil, errors.New("unknown cipher method: ", server.Cipher)
|
||||||
}
|
}
|
||||||
ss := &protocol.ServerEndpoint{
|
ss := &protocol.ServerEndpoint{
|
||||||
Address: v.Address.Build(),
|
Address: server.Address.Build(),
|
||||||
Port: uint32(v.Port),
|
Port: uint32(server.Port),
|
||||||
User: &protocol.User{
|
User: &protocol.User{
|
||||||
Level: uint32(v.Level),
|
Level: uint32(server.Level),
|
||||||
Email: v.Email,
|
Email: server.Email,
|
||||||
Account: serial.ToTypedMessage(&shadowsocks.Account{
|
Account: serial.ToTypedMessage(account),
|
||||||
Password: v.Password,
|
|
||||||
CipherType: cipherFromString(v.Cipher),
|
|
||||||
}),
|
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
config.Server = ss
|
config.Server = ss
|
||||||
|
|||||||
+61
-22
@@ -1,6 +1,9 @@
|
|||||||
package conf
|
package conf
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/protocol"
|
"github.com/xtls/xray-core/common/protocol"
|
||||||
"github.com/xtls/xray-core/common/serial"
|
"github.com/xtls/xray-core/common/serial"
|
||||||
"github.com/xtls/xray-core/proxy/socks"
|
"github.com/xtls/xray-core/proxy/socks"
|
||||||
@@ -64,35 +67,71 @@ func (v *SocksServerConfig) Build() (proto.Message, error) {
|
|||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SocksRemoteConfig struct {
|
||||||
|
Address *Address `json:"address"`
|
||||||
|
Port uint16 `json:"port"`
|
||||||
|
Users []json.RawMessage `json:"users"`
|
||||||
|
}
|
||||||
|
|
||||||
type SocksClientConfig struct {
|
type SocksClientConfig struct {
|
||||||
Address Address `json:"address"`
|
Address *Address `json:"address"`
|
||||||
Port uint16 `json:"port"`
|
Port uint16 `json:"port"`
|
||||||
Level uint32 `json:"level"`
|
Level uint32 `json:"level"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Username string `json:"user"`
|
Username string `json:"user"`
|
||||||
Password string `json:"pass"`
|
Password string `json:"pass"`
|
||||||
|
Servers []*SocksRemoteConfig `json:"servers"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (v *SocksClientConfig) Build() (proto.Message, error) {
|
func (v *SocksClientConfig) Build() (proto.Message, error) {
|
||||||
config := new(socks.ClientConfig)
|
config := new(socks.ClientConfig)
|
||||||
|
if v.Address != nil {
|
||||||
server := &protocol.ServerEndpoint{
|
v.Servers = []*SocksRemoteConfig{
|
||||||
Address: v.Address.Build(),
|
{
|
||||||
Port: uint32(v.Port),
|
Address: v.Address,
|
||||||
}
|
Port: v.Port,
|
||||||
if len(v.Username) > 0 {
|
},
|
||||||
account := &SocksAccount{
|
|
||||||
Username: v.Username,
|
|
||||||
Password: v.Password,
|
|
||||||
}
|
}
|
||||||
user := &protocol.User{
|
if len(v.Username) > 0 {
|
||||||
Level: v.Level,
|
v.Servers[0].Users = []json.RawMessage{{}}
|
||||||
Email: v.Email,
|
|
||||||
Account: serial.ToTypedMessage(account.Build()),
|
|
||||||
}
|
}
|
||||||
server.User = user
|
|
||||||
}
|
}
|
||||||
|
if len(v.Servers) != 1 {
|
||||||
config.Server = server
|
return nil, errors.New(`SOCKS settings: "servers" should have one and only one member. Multiple endpoints in "servers" should use multiple SOCKS outbounds and routing balancer instead`)
|
||||||
|
}
|
||||||
|
for _, serverConfig := range v.Servers {
|
||||||
|
if len(serverConfig.Users) > 1 {
|
||||||
|
return nil, errors.New(`SOCKS servers: "users" should have one member at most. Multiple members in "users" should use multiple SOCKS outbounds and routing balancer instead`)
|
||||||
|
}
|
||||||
|
server := &protocol.ServerEndpoint{
|
||||||
|
Address: serverConfig.Address.Build(),
|
||||||
|
Port: uint32(serverConfig.Port),
|
||||||
|
}
|
||||||
|
for _, rawUser := range serverConfig.Users {
|
||||||
|
user := new(protocol.User)
|
||||||
|
if v.Address != nil {
|
||||||
|
user.Level = v.Level
|
||||||
|
user.Email = v.Email
|
||||||
|
} else {
|
||||||
|
if err := json.Unmarshal(rawUser, user); err != nil {
|
||||||
|
return nil, errors.New("failed to parse Socks user").Base(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
account := new(SocksAccount)
|
||||||
|
if v.Address != nil {
|
||||||
|
account.Username = v.Username
|
||||||
|
account.Password = v.Password
|
||||||
|
} else {
|
||||||
|
if err := json.Unmarshal(rawUser, account); err != nil {
|
||||||
|
return nil, errors.New("failed to parse socks account").Base(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
user.Account = serial.ToTypedMessage(account.Build())
|
||||||
|
server.User = user
|
||||||
|
break
|
||||||
|
}
|
||||||
|
config.Server = server
|
||||||
|
break
|
||||||
|
}
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,6 +53,35 @@ func TestSocksOutboundConfig(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
runMultiTestCase(t, []TestCase{
|
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: `{
|
Input: `{
|
||||||
"address": "127.0.0.1",
|
"address": "127.0.0.1",
|
||||||
|
|||||||
@@ -929,9 +929,6 @@ func (c *XDNS) Build() (proto.Message, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
quicConfig = proto.(*internet.QuicParams)
|
quicConfig = proto.(*internet.QuicParams)
|
||||||
if quicConfig.Congestion == "brutal" {
|
|
||||||
return nil, errors.New(`XDNS: "brutal" is for Hysteria, use "force-brutal", "bbr" or "reno"`)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
for j := range c.Resolvers[i].Addrs {
|
for j := range c.Resolvers[i].Addrs {
|
||||||
var u *url.URL
|
var u *url.URL
|
||||||
@@ -978,17 +975,6 @@ type XMC struct {
|
|||||||
// NoPadding disables padding. An explicit empty "paddings" array means the
|
// NoPadding disables padding. An explicit empty "paddings" array means the
|
||||||
// same; an absent one keeps the built-in preset.
|
// same; an absent one keeps the built-in preset.
|
||||||
NoPadding bool `json:"noPadding,omitempty"`
|
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 {
|
type XMCPaddingTurn struct {
|
||||||
@@ -1054,21 +1040,7 @@ func (c *XMC) Build() (proto.Message, error) {
|
|||||||
if noPadding && len(c.Paddings) > 0 {
|
if noPadding && len(c.Paddings) > 0 {
|
||||||
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
|
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
|
||||||
}
|
}
|
||||||
if err := xmc.ValidateProtocolVersion(c.ProtocolVersion); err != nil {
|
config := &xmc.Config{Hostname: c.Hostname, NoPadding: noPadding}
|
||||||
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 {
|
for i, turn := range c.Paddings {
|
||||||
minimum, maximum, err := ParseRangeString(turn.Length)
|
minimum, maximum, err := ParseRangeString(turn.Length)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -242,93 +242,3 @@ func TestXMCBuildDisablesPadding(t *testing.T) {
|
|||||||
t.Fatalf("expected an exclusive padding error, got %v", err)
|
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)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -277,9 +277,6 @@ func (c *StreamConfig) Build() (*internet.StreamConfig, error) {
|
|||||||
return nil, errors.New(`XDRIVE: brutal is for Hysteria servers, over h3 "congestion" is "bbr" or "reno", not "`, config.QuicParams.Congestion, `"`)
|
return nil, errors.New(`XDRIVE: brutal is for Hysteria servers, over h3 "congestion" is "bbr" or "reno", not "`, config.QuicParams.Congestion, `"`)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if config.ProtocolName == "splithttp" && config.QuicParams != nil && config.QuicParams.Congestion == "brutal" {
|
|
||||||
return nil, errors.New(`XHTTP: "brutal" is for Hysteria, use "force-brutal", "bbr" or "reno"`)
|
|
||||||
}
|
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -455,9 +455,6 @@ func (c *SplitHTTPConfig) Build() (proto.Message, error) {
|
|||||||
if c.ServerMaxHeaderBytes < 0 {
|
if c.ServerMaxHeaderBytes < 0 {
|
||||||
return nil, errors.New("invalid negative value of maxHeaderBytes")
|
return nil, errors.New("invalid negative value of maxHeaderBytes")
|
||||||
}
|
}
|
||||||
if c.ScMaxEachPostBytes.From < 0 || c.ScMaxEachPostBytes.To < 0 || (c.ScMaxEachPostBytes.To > 0 && c.ScMaxEachPostBytes.From <= 0) {
|
|
||||||
return nil, errors.New("`scMaxEachPostBytes` must be greater than 0")
|
|
||||||
}
|
|
||||||
|
|
||||||
if c.Xmux.MaxConnections.To > 0 && c.Xmux.MaxConcurrency.To > 0 {
|
if c.Xmux.MaxConnections.To > 0 && c.Xmux.MaxConcurrency.To > 0 {
|
||||||
return nil, errors.New("maxConnections cannot be specified together with maxConcurrency")
|
return nil, errors.New("maxConnections cannot be specified together with maxConcurrency")
|
||||||
|
|||||||
@@ -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}}, ` + xdriveStream + `}`,
|
||||||
`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpConcurrency": 8, "xudpProxyUDP443": "allow"}}, ` + 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": {` + xdriveServer + `, ` + xdriveEnc + `, "reverse": {"tag": "r"}}, ` + xdriveStream + `}`,
|
||||||
`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`,
|
||||||
} {
|
} {
|
||||||
if err := build(input); err != nil {
|
if err := build(input); err != nil {
|
||||||
t.Errorf("%s: %v", input, err)
|
t.Errorf("%s: %v", input, err)
|
||||||
@@ -541,9 +541,12 @@ func TestXDriveOutboundConfig(t *testing.T) {
|
|||||||
for _, c := range []struct{ input, err string }{
|
for _, c := range []struct{ input, err string }{
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
{`{"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": {"address": "example.com", "port": 443, ` + xdriveID + `, "encryption": "none", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"encryption"`},
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"xudpProxyUDP443":"skip"`},
|
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||||
|
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, `"settings.multiplex.concurrency"`},
|
||||||
|
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"xudpConcurrency": 8}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||||
|
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "multiplex": {"concurrency": 8, "xudpProxyUDP443": "skip"}}, ` + xdriveStream + `}`, `"settings.multiplex.concurrency"`},
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||||
{`{"protocol": "vless", "settings": {"address": "127.0.0.1", "port": 443, ` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision", "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
{`{"protocol": "vless", "settings": {"vnext": [{"address": "127.0.0.1", "port": 443, "users": [{` + xdriveID + `, ` + xdriveEnc + `, "flow": "xtls-rprx-vision"}]}], "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"flow"`},
|
||||||
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`},
|
{`{"protocol": "vless", "settings": {` + xdriveServer + `, ` + xdriveEnc + `, "testpre": 1, "multiplex": {"concurrency": 8}}, ` + xdriveStream + `}`, `"testpre"`},
|
||||||
{`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
{`{"protocol": "vmess", "settings": {` + xdriveServer + `}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||||
{`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
{`{"protocol": "trojan", "settings": {"address": "example.com", "port": 443, "password": "p"}, ` + xdriveStream + `, "mux": {"enabled": true}}`, "VLESS"},
|
||||||
|
|||||||
+63
-21
@@ -17,38 +17,76 @@ import (
|
|||||||
"google.golang.org/protobuf/proto"
|
"google.golang.org/protobuf/proto"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// TrojanServerTarget is configuration of a single trojan server
|
||||||
|
type TrojanServerTarget struct {
|
||||||
|
Address *Address `json:"address"`
|
||||||
|
Port uint16 `json:"port"`
|
||||||
|
Level byte `json:"level"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
Password string `json:"password"`
|
||||||
|
Flow string `json:"flow"`
|
||||||
|
}
|
||||||
|
|
||||||
// TrojanClientConfig is configuration of trojan servers
|
// TrojanClientConfig is configuration of trojan servers
|
||||||
type TrojanClientConfig struct {
|
type TrojanClientConfig struct {
|
||||||
Address Address `json:"address"`
|
Address *Address `json:"address"`
|
||||||
Port uint16 `json:"port"`
|
Port uint16 `json:"port"`
|
||||||
Level byte `json:"level"`
|
Level byte `json:"level"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
|
Flow string `json:"flow"`
|
||||||
|
Servers []*TrojanServerTarget `json:"servers"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build implements Buildable
|
// Build implements Buildable
|
||||||
func (c *TrojanClientConfig) Build() (proto.Message, error) {
|
func (c *TrojanClientConfig) Build() (proto.Message, error) {
|
||||||
errors.PrintNonRemovalDeprecatedFeatureWarning("Trojan (with no Flow, etc.)", "VLESS with Flow & Seed")
|
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{}
|
config := &trojan.ClientConfig{}
|
||||||
|
|
||||||
if c.Port == 0 {
|
for _, rec := range c.Servers {
|
||||||
return nil, errors.New("Invalid Trojan port.")
|
if rec.Address == nil {
|
||||||
}
|
return nil, errors.New("Trojan server address is not set.")
|
||||||
if c.Password == "" {
|
}
|
||||||
return nil, errors.New("Trojan password is not specified.")
|
if rec.Port == 0 {
|
||||||
}
|
return nil, errors.New("Invalid Trojan port.")
|
||||||
|
}
|
||||||
|
if rec.Password == "" {
|
||||||
|
return nil, errors.New("Trojan password is not specified.")
|
||||||
|
}
|
||||||
|
if rec.Flow != "" {
|
||||||
|
return nil, errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
|
||||||
|
}
|
||||||
|
|
||||||
config.Server = &protocol.ServerEndpoint{
|
config.Server = &protocol.ServerEndpoint{
|
||||||
Address: c.Address.Build(),
|
Address: rec.Address.Build(),
|
||||||
Port: uint32(c.Port),
|
Port: uint32(rec.Port),
|
||||||
User: &protocol.User{
|
User: &protocol.User{
|
||||||
Level: uint32(c.Level),
|
Level: uint32(rec.Level),
|
||||||
Email: c.Email,
|
Email: rec.Email,
|
||||||
Account: serial.ToTypedMessage(&trojan.Account{
|
Account: serial.ToTypedMessage(&trojan.Account{
|
||||||
Password: c.Password,
|
Password: rec.Password,
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
return config, nil
|
return config, nil
|
||||||
@@ -69,6 +107,7 @@ type TrojanUserConfig struct {
|
|||||||
Password string `json:"password"`
|
Password string `json:"password"`
|
||||||
Level byte `json:"level"`
|
Level byte `json:"level"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
|
Flow string `json:"flow"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// TrojanServerConfig is Inbound configuration
|
// TrojanServerConfig is Inbound configuration
|
||||||
@@ -92,6 +131,9 @@ func (c *TrojanServerConfig) Build() (proto.Message, error) {
|
|||||||
|
|
||||||
processClient := func(idx int) error {
|
processClient := func(idx int) error {
|
||||||
rawUser := c.Users[idx]
|
rawUser := c.Users[idx]
|
||||||
|
if rawUser.Flow != "" {
|
||||||
|
return errors.PrintRemovedFeatureError(`Flow for Trojan`, ``)
|
||||||
|
}
|
||||||
|
|
||||||
config.Users[idx] = &protocol.User{
|
config.Users[idx] = &protocol.User{
|
||||||
Level: uint32(rawUser.Level),
|
Level: uint32(rawUser.Level),
|
||||||
|
|||||||
@@ -159,7 +159,6 @@ func TestTunConfigGUID(t *testing.T) {
|
|||||||
for _, guid := range []string{
|
for _, guid := range []string{
|
||||||
"xray0",
|
"xray0",
|
||||||
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
|
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
|
||||||
"6ba7b8109-dad-11d1-80b4-00c04fd430c8", // the right length, a hyphen out of place
|
|
||||||
"6ba7b8109dad11d180b400c04fd430c8",
|
"6ba7b8109dad11d180b400c04fd430c8",
|
||||||
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
|
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
|
||||||
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
||||||
|
|||||||
+190
-150
@@ -104,15 +104,56 @@ func (c *VLessInboundConfig) Build() (proto.Message, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
dec, err := parseVLESSEncryption(c.Decryption, false)
|
config.Decryption = c.Decryption
|
||||||
if err != nil {
|
if !func() bool {
|
||||||
return nil, err
|
s := strings.Split(config.Decryption, ".")
|
||||||
|
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
switch s[1] {
|
||||||
|
case "native":
|
||||||
|
case "xorpub":
|
||||||
|
config.XorMode = 1
|
||||||
|
case "random":
|
||||||
|
config.XorMode = 2
|
||||||
|
default:
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
t := strings.SplitN(strings.TrimSuffix(s[2], "s"), "-", 2)
|
||||||
|
i, err := strconv.Atoi(t[0])
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
config.SecondsFrom = int64(i)
|
||||||
|
if len(t) == 2 {
|
||||||
|
i, err := strconv.Atoi(t[1])
|
||||||
|
if err != nil {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
config.SecondsTo = int64(i)
|
||||||
|
}
|
||||||
|
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) != 64 {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
config.Decryption = config.Decryption[27+len(s[2]):]
|
||||||
|
if padding > 0 {
|
||||||
|
config.Padding = config.Decryption[:padding-1]
|
||||||
|
config.Decryption = config.Decryption[padding:]
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
}() && config.Decryption != "none" {
|
||||||
|
if config.Decryption == "" {
|
||||||
|
return nil, errors.New(`VLESS settings: please add/set "decryption":"none" to every settings`)
|
||||||
|
}
|
||||||
|
return nil, errors.New(`VLESS settings: unsupported "decryption": ` + config.Decryption)
|
||||||
}
|
}
|
||||||
config.Decryption = dec.key
|
|
||||||
config.Padding = dec.padding
|
|
||||||
config.XorMode = dec.xorMode
|
|
||||||
config.SecondsFrom = dec.secondsFrom
|
|
||||||
config.SecondsTo = dec.secondsTo
|
|
||||||
|
|
||||||
if config.Decryption != "none" && c.Fallbacks != nil {
|
if config.Decryption != "none" && c.Fallbacks != nil {
|
||||||
return nil, errors.New(`VLESS settings: "fallbacks" can not be used together with "decryption"`)
|
return nil, errors.New(`VLESS settings: "fallbacks" can not be used together with "decryption"`)
|
||||||
@@ -215,19 +256,26 @@ func (c *MultiplexConfig) Build() (*vless.Multiplex, error) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type VLessOutboundVnext struct {
|
||||||
|
Address *Address `json:"address"`
|
||||||
|
Port uint16 `json:"port"`
|
||||||
|
Users []json.RawMessage `json:"users"`
|
||||||
|
}
|
||||||
|
|
||||||
type VLessOutboundConfig struct {
|
type VLessOutboundConfig struct {
|
||||||
Address Address `json:"address"`
|
Address *Address `json:"address"`
|
||||||
Port uint16 `json:"port"`
|
Port uint16 `json:"port"`
|
||||||
Level uint32 `json:"level"`
|
Level uint32 `json:"level"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
Id string `json:"id"`
|
Id string `json:"id"`
|
||||||
Flow string `json:"flow"`
|
Flow string `json:"flow"`
|
||||||
Seed string `json:"seed"`
|
Seed string `json:"seed"`
|
||||||
Encryption string `json:"encryption"`
|
Encryption string `json:"encryption"`
|
||||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||||
Reverse *VLessReverseConfig `json:"reverse"`
|
Reverse *VLessReverseConfig `json:"reverse"`
|
||||||
Testpre uint32 `json:"testpre"`
|
Testpre uint32 `json:"testpre"`
|
||||||
Testseed []uint32 `json:"testseed"`
|
Testseed []uint32 `json:"testseed"`
|
||||||
|
Vnext []*VLessOutboundVnext `json:"vnext"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build implements Buildable
|
// Build implements Buildable
|
||||||
@@ -238,138 +286,130 @@ func (c *VLessOutboundConfig) Build() (proto.Message, error) {
|
|||||||
}
|
}
|
||||||
config := &outbound.Config{Multiplex: multiplex}
|
config := &outbound.Config{Multiplex: multiplex}
|
||||||
|
|
||||||
uid, err := uuid.ParseString(c.Id)
|
if c.Address != nil {
|
||||||
if err != nil {
|
c.Vnext = []*VLessOutboundVnext{
|
||||||
return nil, err
|
{
|
||||||
}
|
Address: c.Address,
|
||||||
|
Port: c.Port,
|
||||||
switch c.Flow {
|
Users: []json.RawMessage{{}},
|
||||||
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 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
|
||||||
}
|
}
|
||||||
|
|
||||||
enc, err := parseVLESSEncryption(account.Encryption, true)
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
account.Encryption = enc.key
|
|
||||||
account.Padding = enc.padding
|
|
||||||
account.XorMode = enc.xorMode
|
|
||||||
account.Seconds = enc.seconds
|
|
||||||
|
|
||||||
user.Account = serial.ToTypedMessage(account)
|
|
||||||
spec.User = user
|
|
||||||
|
|
||||||
config.Vnext = spec
|
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
type parsedVLESSEncryption struct {
|
|
||||||
key string
|
|
||||||
padding string
|
|
||||||
xorMode uint32
|
|
||||||
seconds uint32
|
|
||||||
secondsFrom int64
|
|
||||||
secondsTo int64
|
|
||||||
}
|
|
||||||
|
|
||||||
func parseVLESSEncryption(raw string, isOutbound bool) (parsedVLESSEncryption, error) {
|
|
||||||
field, scope := "decryption", "settings"
|
|
||||||
if isOutbound {
|
|
||||||
field, scope = "encryption", "users"
|
|
||||||
}
|
|
||||||
if raw == "" {
|
|
||||||
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: please add/set "`, field, `":"none"`)
|
|
||||||
}
|
|
||||||
if raw == "none" {
|
|
||||||
return parsedVLESSEncryption{key: "none"}, nil
|
|
||||||
}
|
|
||||||
s := strings.Split(raw, ".")
|
|
||||||
if len(s) < 4 || s[0] != "mlkem768x25519plus" {
|
|
||||||
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: unsupported "`, field, `": `, raw)
|
|
||||||
}
|
|
||||||
var out parsedVLESSEncryption
|
|
||||||
switch s[1] {
|
|
||||||
case "native":
|
|
||||||
case "xorpub":
|
|
||||||
out.xorMode = 1
|
|
||||||
case "random":
|
|
||||||
out.xorMode = 2
|
|
||||||
default:
|
|
||||||
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: unsupported "`, field, `" mode: `, s[1])
|
|
||||||
}
|
|
||||||
if isOutbound {
|
|
||||||
switch s[2] {
|
|
||||||
case "1rtt":
|
|
||||||
case "0rtt":
|
|
||||||
out.seconds = 1
|
|
||||||
default:
|
|
||||||
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: unsupported "`, field, `" rtt: `, s[2])
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
t := strings.SplitN(strings.TrimSuffix(s[2], "s"), "-", 2)
|
|
||||||
i, err := strconv.Atoi(t[0])
|
|
||||||
if err != nil {
|
|
||||||
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: invalid "`, field, `" seconds: `, s[2]).Base(err)
|
|
||||||
}
|
|
||||||
out.secondsFrom = int64(i)
|
|
||||||
if len(t) == 2 {
|
|
||||||
i, err := strconv.Atoi(t[1])
|
|
||||||
if err != nil {
|
|
||||||
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: invalid "`, field, `" seconds: `, s[2]).Base(err)
|
|
||||||
}
|
|
||||||
out.secondsTo = int64(i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
altKeyLen := 64
|
|
||||||
if isOutbound {
|
|
||||||
altKeyLen = 1184
|
|
||||||
}
|
|
||||||
padding := 0
|
|
||||||
for i, r := range s[3:] {
|
|
||||||
if len(r) < 20 {
|
|
||||||
padding += len(r) + 1
|
|
||||||
continue
|
|
||||||
}
|
|
||||||
for _, r := range s[3+i:] {
|
|
||||||
b, err := base64.RawURLEncoding.DecodeString(r)
|
|
||||||
if err != nil || (len(b) != 32 && len(b) != altKeyLen) {
|
|
||||||
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: invalid "`, field, `" key segment`)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
rest := raw[27+len(s[2]):]
|
|
||||||
if padding > 0 {
|
|
||||||
out.padding = rest[:padding-1]
|
|
||||||
rest = rest[padding:]
|
|
||||||
}
|
|
||||||
out.key = rest
|
|
||||||
return out, nil
|
|
||||||
}
|
|
||||||
return parsedVLESSEncryption{}, errors.New(`VLESS `, scope, `: missing "`, field, `" key segment`)
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -18,6 +18,41 @@ func TestVLessOutbound(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
runMultiTestCase(t, []TestCase{
|
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: `{
|
Input: `{
|
||||||
"address": "example.com",
|
"address": "example.com",
|
||||||
|
|||||||
+69
-27
@@ -102,15 +102,22 @@ func (c *VMessInboundConfig) Build() (proto.Message, error) {
|
|||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type VMessOutboundTarget struct {
|
||||||
|
Address *Address `json:"address"`
|
||||||
|
Port uint16 `json:"port"`
|
||||||
|
Users []json.RawMessage `json:"users"`
|
||||||
|
}
|
||||||
|
|
||||||
type VMessOutboundConfig struct {
|
type VMessOutboundConfig struct {
|
||||||
Address Address `json:"address"`
|
Address *Address `json:"address"`
|
||||||
Port uint16 `json:"port"`
|
Port uint16 `json:"port"`
|
||||||
Level uint32 `json:"level"`
|
Level uint32 `json:"level"`
|
||||||
Email string `json:"email"`
|
Email string `json:"email"`
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
Security string `json:"security"`
|
Security string `json:"security"`
|
||||||
Experiments string `json:"experiments"`
|
Experiments string `json:"experiments"`
|
||||||
Multiplex *MultiplexConfig `json:"multiplex"`
|
Receivers []*VMessOutboundTarget `json:"vnext"`
|
||||||
|
Multiplex *MultiplexConfig `json:"multiplex"`
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build implements Buildable
|
// Build implements Buildable
|
||||||
@@ -122,27 +129,62 @@ func (c *VMessOutboundConfig) Build() (proto.Message, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
config := &outbound.Config{Multiplex: multiplex}
|
config := &outbound.Config{Multiplex: multiplex}
|
||||||
|
if c.Address != nil {
|
||||||
uid, err := uuid.ParseString(c.ID)
|
c.Receivers = []*VMessOutboundTarget{
|
||||||
if err != nil {
|
{
|
||||||
return nil, err
|
Address: c.Address,
|
||||||
|
Port: c.Port,
|
||||||
|
Users: []json.RawMessage{{}},
|
||||||
|
},
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
if len(c.Receivers) != 1 {
|
||||||
account := &VMessAccount{
|
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`)
|
||||||
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()),
|
|
||||||
},
|
|
||||||
}
|
}
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
config.Receiver = spec
|
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
|
||||||
|
}
|
||||||
return config, nil
|
return config, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -18,6 +18,42 @@ func TestVMessOutbound(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
runMultiTestCase(t, []TestCase{
|
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: `{
|
Input: `{
|
||||||
"address": "127.0.0.1",
|
"address": "127.0.0.1",
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package conf
|
|||||||
import (
|
import (
|
||||||
"encoding/base64"
|
"encoding/base64"
|
||||||
"encoding/hex"
|
"encoding/hex"
|
||||||
"net/netip"
|
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
@@ -125,12 +124,6 @@ func (c *WireGuardConfig) Build() (proto.Message, error) {
|
|||||||
}
|
}
|
||||||
config.Reserved = c.Reserved
|
config.Reserved = c.Reserved
|
||||||
|
|
||||||
for _, s := range c.DNS {
|
|
||||||
if _, err := netip.ParseAddr(s); err != nil {
|
|
||||||
return nil, errors.New(`WireGuard: invalid "remoteDNS" `, s).Base(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
config.IsClient = c.IsClient
|
config.IsClient = c.IsClient
|
||||||
config.NoKernelTun = c.NoKernelTun
|
config.NoKernelTun = c.NoKernelTun
|
||||||
config.DNS = c.DNS
|
config.DNS = c.DNS
|
||||||
|
|||||||
+5
-15
@@ -232,13 +232,13 @@ func validateOutboundTransportSecurity(rawConfig interface{}, senderSettings *pr
|
|||||||
if vlessCfg.Encryption != "" && vlessCfg.Encryption != "none" {
|
if vlessCfg.Encryption != "" && vlessCfg.Encryption != "none" {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if requiresTransportSecurity(&vlessCfg.Address) {
|
if requiresTransportSecurity(vlessCfg.Address) {
|
||||||
return errors.New("vless without TLS or other encryption is prohibited unless the server address is a private IP or domain")
|
return errors.New("vless without TLS or other encryption is prohibited unless the server address is a private IP or domain")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
|
if tjCfg, ok := rawConfig.(*TrojanClientConfig); ok {
|
||||||
if requiresTransportSecurity(&tjCfg.Address) {
|
if requiresTransportSecurity(tjCfg.Servers[0].Address) {
|
||||||
return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain")
|
return errors.New("trojan without TLS is prohibited unless the server address is a private IP or domain")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -265,13 +265,8 @@ func validateXDrive(ts proto.Message, ss *internet.StreamConfig, pl *net.PortLis
|
|||||||
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
|
return errors.New(`the xdrive transport needs VLESS "encryption", run "xray vlessenc" to get one`)
|
||||||
}
|
}
|
||||||
// Reverse opens its own multiplexed connection.
|
// Reverse opens its own multiplexed connection.
|
||||||
if account.Reverse == nil {
|
if account.Reverse == nil && (c.Multiplex.GetConcurrency() == 0 || c.Multiplex.GetXudpProxyUDP443() == "skip") {
|
||||||
if c.Multiplex == nil {
|
return errors.New(`the xdrive transport needs positive "settings.multiplex.concurrency" and does not support "xudpProxyUDP443":"skip"`)
|
||||||
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 {
|
if account.Testpre != 0 {
|
||||||
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
return errors.New(`the xdrive transport doesn't support VLESS "testpre"`)
|
||||||
@@ -372,15 +367,10 @@ func (c *OutboundDetourConfig) Build() (*core.OutboundHandlerConfig, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("failed to build outbound handler for protocol ", c.Protocol).Base(err)
|
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 {
|
if err := validateXDrive(ts, senderSettings.StreamSettings, nil); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
if err := validateOutboundTransportSecurity(rawConfig, senderSettings); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
package proxy
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"math/rand/v2"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common"
|
|
||||||
"github.com/xtls/xray-core/common/buf"
|
|
||||||
"github.com/xtls/xray-core/common/signal"
|
|
||||||
)
|
|
||||||
|
|
||||||
// wait to drain all the possible incoming UDP data
|
|
||||||
// because re-established QUIC UDP may bypass the sniffer
|
|
||||||
func DropUDP(ctx context.Context, reader buf.Reader) {
|
|
||||||
ctx, cancel := context.WithCancel(ctx)
|
|
||||||
timer := signal.CancelAfterInactivity(ctx, func() {
|
|
||||||
cancel()
|
|
||||||
}, time.Duration(30+rand.N(60))*time.Second)
|
|
||||||
context.AfterFunc(ctx, func() {
|
|
||||||
common.Interrupt(reader)
|
|
||||||
})
|
|
||||||
buf.Copy(reader, buf.Discard, buf.UpdateActivity(timer))
|
|
||||||
}
|
|
||||||
+14
-39
@@ -5,7 +5,6 @@ import (
|
|||||||
go_errors "errors"
|
go_errors "errors"
|
||||||
"io"
|
"io"
|
||||||
"math/rand"
|
"math/rand"
|
||||||
"slices"
|
|
||||||
|
|
||||||
"github.com/apernet/quic-go"
|
"github.com/apernet/quic-go"
|
||||||
"github.com/xtls/xray-core/common"
|
"github.com/xtls/xray-core/common"
|
||||||
@@ -175,15 +174,10 @@ func init() {
|
|||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
|
|
||||||
// UDPWriter is not safe for concurrent writes.
|
|
||||||
type UDPWriter struct {
|
type UDPWriter struct {
|
||||||
writer io.Writer
|
writer io.Writer
|
||||||
addr string
|
addr string
|
||||||
buf [buf.Size]byte
|
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 {
|
func (w *UDPWriter) SendMessage(msg *UDPMessage) error {
|
||||||
@@ -199,21 +193,21 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
|||||||
for i, b := range mb {
|
for i, b := range mb {
|
||||||
addr := w.addr
|
addr := w.addr
|
||||||
if b.UDP != nil {
|
if b.UDP != nil {
|
||||||
if *b.UDP != w.lastUDP {
|
addr = b.UDP.NetAddr()
|
||||||
w.lastUDP = *b.UDP
|
|
||||||
w.lastUDPAddr = b.UDP.NetAddr()
|
|
||||||
}
|
|
||||||
addr = w.lastUDPAddr
|
|
||||||
}
|
}
|
||||||
|
|
||||||
msg := &UDPMessage{
|
msg := &UDPMessage{
|
||||||
|
SessionID: 0,
|
||||||
|
PacketID: 0,
|
||||||
|
FragID: 0,
|
||||||
FragCount: 1,
|
FragCount: 1,
|
||||||
Addr: addr,
|
Addr: addr,
|
||||||
Data: b.Bytes(),
|
Data: b.Bytes(),
|
||||||
}
|
}
|
||||||
|
|
||||||
err := w.SendMessage(msg)
|
err := w.SendMessage(msg)
|
||||||
if errTooLarge, ok := go_errors.AsType[*quic.DatagramTooLargeError](err); ok {
|
var errTooLarge *quic.DatagramTooLargeError
|
||||||
|
if go_errors.As(err, &errTooLarge) {
|
||||||
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
|
msg.PacketID = uint16(rand.Intn(0xFFFF)) + 1
|
||||||
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
|
fMsgs := FragUDPMessage(msg, int(errTooLarge.MaxDatagramPayloadSize))
|
||||||
for _, fMsg := range fMsgs {
|
for _, fMsg := range fMsgs {
|
||||||
@@ -234,59 +228,40 @@ func (w *UDPWriter) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// UDPReader is not safe for concurrent reads.
|
|
||||||
type UDPReader struct {
|
type UDPReader struct {
|
||||||
reader io.Reader
|
reader io.Reader
|
||||||
df *Defragger
|
df *Defragger
|
||||||
firstBuf *buf.Buffer
|
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) {
|
func (r *UDPReader) ReadFrom(p []byte) (n int, addr *net.Destination, err error) {
|
||||||
for {
|
for {
|
||||||
n, err := r.reader.Read(r.packet[:])
|
var packet [1500]byte
|
||||||
|
|
||||||
|
n, err := r.reader.Read(packet[:])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, nil, err
|
return 0, nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if err := parseUDPMessage(r.packet[:n], r.lastAddr, &r.msg); err != nil {
|
msg, err := ParseUDPMessage(packet[:n])
|
||||||
|
if err != nil {
|
||||||
continue
|
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)
|
dfMsg := r.df.Feed(msg)
|
||||||
if dfMsg == nil {
|
if dfMsg == nil {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
if dfMsg.Addr != r.lastAddr {
|
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
||||||
dest, err := net.ParseDestination("udp:" + dfMsg.Addr)
|
if err != nil {
|
||||||
if err != nil {
|
continue
|
||||||
continue
|
|
||||||
}
|
|
||||||
r.lastAddr = dfMsg.Addr
|
|
||||||
r.lastDest = dest
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(p) < len(dfMsg.Data) {
|
if len(p) < len(dfMsg.Data) {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
|
|
||||||
// Callers can rewrite the packet destination in place.
|
|
||||||
dest := r.lastDest
|
|
||||||
return copy(p, dfMsg.Data), &dest, nil
|
return copy(p, dfMsg.Data), &dest, nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,147 +0,0 @@
|
|||||||
package hysteria
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"io"
|
|
||||||
"testing"
|
|
||||||
|
|
||||||
"github.com/apernet/quic-go"
|
|
||||||
"github.com/xtls/xray-core/common/buf"
|
|
||||||
xnet "github.com/xtls/xray-core/common/net"
|
|
||||||
)
|
|
||||||
|
|
||||||
// datagramReader returns one datagram per Read, like a QUIC datagram stream.
|
|
||||||
type datagramReader struct {
|
|
||||||
msgs [][]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *datagramReader) Read(p []byte) (int, error) {
|
|
||||||
if len(r.msgs) == 0 {
|
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
n := copy(p, r.msgs[0])
|
|
||||||
r.msgs = r.msgs[1:]
|
|
||||||
return n, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func newTestReader(msgs []UDPMessage) *UDPReader {
|
|
||||||
datagrams := make([][]byte, len(msgs))
|
|
||||||
for i := range msgs {
|
|
||||||
datagrams[i] = make([]byte, msgs[i].Size())
|
|
||||||
msgs[i].Serialize(datagrams[i])
|
|
||||||
}
|
|
||||||
return &UDPReader{reader: &datagramReader{msgs: datagrams}, df: &Defragger{}}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestUDPReaderFragments(t *testing.T) {
|
|
||||||
want := &UDPMessage{PacketID: 1, Addr: "example.com:443", Data: bytes.Repeat([]byte("0123456789"), 20)}
|
|
||||||
frags := FragUDPMessage(want, 100)
|
|
||||||
if len(frags) < 2 {
|
|
||||||
t.Fatalf("got %d fragments, want at least 2", len(frags))
|
|
||||||
}
|
|
||||||
|
|
||||||
p := make([]byte, buf.Size)
|
|
||||||
n, dest, err := newTestReader(frags).ReadFrom(p)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
|
||||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, want.Data, want.Addr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestUDPReaderDestinations(t *testing.T) {
|
|
||||||
msgs := []UDPMessage{
|
|
||||||
{Addr: "203.0.113.1:53", Data: []byte("first")},
|
|
||||||
{Addr: "203.0.113.1:53", Data: []byte("second")},
|
|
||||||
{Addr: "203.0.113.2:53", Data: []byte("third")},
|
|
||||||
}
|
|
||||||
r := newTestReader(msgs)
|
|
||||||
p := make([]byte, buf.Size)
|
|
||||||
for i, want := range msgs {
|
|
||||||
n, dest, err := r.ReadFrom(p)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if dest.NetAddr() != want.Addr || !bytes.Equal(p[:n], want.Data) {
|
|
||||||
t.Errorf("packet %d: got %q to %v, want %q to %s", i, p[:n], dest, want.Data, want.Addr)
|
|
||||||
}
|
|
||||||
// Callers rewrite the destination in place, the next packet must not see it.
|
|
||||||
dest.Port = 5353
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
type captureWriter struct {
|
|
||||||
writes [][]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *captureWriter) Write(p []byte) (int, error) {
|
|
||||||
w.writes = append(w.writes, bytes.Clone(p))
|
|
||||||
return len(p), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestUDPWriterAddress(t *testing.T) {
|
|
||||||
ip := xnet.UDPDestination(xnet.ParseAddress("203.0.113.1"), 53)
|
|
||||||
domain := xnet.UDPDestination(xnet.DomainAddress("example.com"), 53)
|
|
||||||
|
|
||||||
cw := &captureWriter{}
|
|
||||||
w := &UDPWriter{writer: cw, addr: "198.51.100.1:1"}
|
|
||||||
for _, tc := range []struct {
|
|
||||||
udp *xnet.Destination
|
|
||||||
want string
|
|
||||||
}{
|
|
||||||
{&ip, "203.0.113.1:53"},
|
|
||||||
{&domain, "example.com:53"},
|
|
||||||
{nil, "198.51.100.1:1"},
|
|
||||||
{&ip, "203.0.113.1:53"},
|
|
||||||
} {
|
|
||||||
b := buf.FromBytes([]byte("data"))
|
|
||||||
b.UDP = tc.udp
|
|
||||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{b}); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
msg, err := ParseUDPMessage(cw.writes[len(cw.writes)-1])
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if msg.Addr != tc.want {
|
|
||||||
t.Errorf("address = %q, want %q", msg.Addr, tc.want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// fragmentingWriter rejects datagrams larger than max, like a QUIC connection.
|
|
||||||
type fragmentingWriter struct {
|
|
||||||
max int
|
|
||||||
writes [][]byte
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *fragmentingWriter) Write(p []byte) (int, error) {
|
|
||||||
if len(p) > w.max {
|
|
||||||
return 0, &quic.DatagramTooLargeError{MaxDatagramPayloadSize: int64(w.max)}
|
|
||||||
}
|
|
||||||
w.writes = append(w.writes, bytes.Clone(p))
|
|
||||||
return len(p), nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestUDPWriterFragmentation(t *testing.T) {
|
|
||||||
data := bytes.Repeat([]byte("0123456789"), 20)
|
|
||||||
fw := &fragmentingWriter{max: 100}
|
|
||||||
w := &UDPWriter{writer: fw, addr: "example.com:443"}
|
|
||||||
if err := w.WriteMultiBuffer(buf.MultiBuffer{buf.FromBytes(data)}); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if len(fw.writes) < 2 {
|
|
||||||
t.Fatalf("got %d datagrams, want at least 2", len(fw.writes))
|
|
||||||
}
|
|
||||||
|
|
||||||
r := &UDPReader{reader: &datagramReader{msgs: fw.writes}, df: &Defragger{}}
|
|
||||||
p := make([]byte, buf.Size)
|
|
||||||
n, dest, err := r.ReadFrom(p)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if dest.NetAddr() != w.addr || !bytes.Equal(p[:n], data) {
|
|
||||||
t.Errorf("got %q to %v, want %q to %s", p[:n], dest, data, w.addr)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
+20
-28
@@ -1,6 +1,7 @@
|
|||||||
package hysteria
|
package hysteria
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"encoding/binary"
|
"encoding/binary"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
@@ -182,44 +183,35 @@ func (m *UDPMessage) Serialize(buf []byte) int {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
|
func ParseUDPMessage(msg []byte) (*UDPMessage, error) {
|
||||||
m := new(UDPMessage)
|
m := &UDPMessage{}
|
||||||
if err := parseUDPMessage(msg, "", m); err != nil {
|
buf := bytes.NewBuffer(msg)
|
||||||
|
if err := binary.Read(buf, binary.BigEndian, &m.SessionID); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return m, nil
|
if err := binary.Read(buf, binary.BigEndian, &m.PacketID); err != nil {
|
||||||
}
|
return nil, err
|
||||||
|
|
||||||
// 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
|
|
||||||
}
|
}
|
||||||
lAddr, n, err := quicvarint.Parse(msg[8:])
|
if err := binary.Read(buf, binary.BigEndian, &m.FragID); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
if err := binary.Read(buf, binary.BigEndian, &m.FragCount); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
lAddr, err := quicvarint.Read(buf)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return nil, err
|
||||||
}
|
}
|
||||||
if lAddr == 0 || lAddr > MaxMessageLength {
|
if lAddr == 0 || lAddr > MaxMessageLength {
|
||||||
return errors.New("invalid address length")
|
return nil, errors.New("invalid address length")
|
||||||
}
|
}
|
||||||
bs := msg[8+n:]
|
bs := buf.Bytes()
|
||||||
if len(bs) <= int(lAddr) {
|
if len(bs) <= int(lAddr) {
|
||||||
// We use <= instead of < here as we expect at least one byte of data after the address
|
// We use <= instead of < here as we expect at least one byte of data after the address
|
||||||
return errors.New("invalid message length")
|
return nil, errors.New("invalid message length")
|
||||||
}
|
}
|
||||||
*m = UDPMessage{
|
m.Addr = string(bs[:lAddr])
|
||||||
SessionID: binary.BigEndian.Uint32(msg),
|
m.Data = bs[lAddr:]
|
||||||
PacketID: binary.BigEndian.Uint16(msg[4:]),
|
return m, nil
|
||||||
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,
|
// varintPut is like quicvarint.Append, but instead of appending to a slice,
|
||||||
|
|||||||
@@ -1,49 +0,0 @@
|
|||||||
package hysteria
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"reflect"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestParseUDPMessage(t *testing.T) {
|
|
||||||
want := &UDPMessage{PacketID: 1, FragID: 2, FragCount: 3, Addr: "example.com:443", Data: []byte("hello")}
|
|
||||||
msg := make([]byte, want.Size())
|
|
||||||
want.Serialize(msg)
|
|
||||||
|
|
||||||
for _, lastAddr := range []string{"", want.Addr, "other:1"} {
|
|
||||||
got := new(UDPMessage)
|
|
||||||
if err := parseUDPMessage(msg, lastAddr, got); err != nil {
|
|
||||||
t.Fatalf("lastAddr %q: %v", lastAddr, err)
|
|
||||||
}
|
|
||||||
if !reflect.DeepEqual(got, want) {
|
|
||||||
t.Errorf("lastAddr %q: got %+v, want %+v", lastAddr, got, want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestParseUDPMessageInvalid(t *testing.T) {
|
|
||||||
msg := &UDPMessage{Addr: "example.com:443", Data: []byte("hello")}
|
|
||||||
buf := make([]byte, msg.Size())
|
|
||||||
msg.Serialize(buf)
|
|
||||||
|
|
||||||
zeroAddrLen := bytes.Clone(buf)
|
|
||||||
zeroAddrLen[8] = 0 // Address length varint follows the 8-byte header
|
|
||||||
|
|
||||||
noData := &UDPMessage{Addr: msg.Addr}
|
|
||||||
noDataBuf := make([]byte, noData.Size())
|
|
||||||
noData.Serialize(noDataBuf)
|
|
||||||
|
|
||||||
for _, tc := range []struct {
|
|
||||||
name string
|
|
||||||
msg []byte
|
|
||||||
}{
|
|
||||||
{"short header", buf[:7]},
|
|
||||||
{"zero address length", zeroAddrLen},
|
|
||||||
{"no data after address", noDataBuf},
|
|
||||||
} {
|
|
||||||
if _, err := ParseUDPMessage(tc.msg); err == nil {
|
|
||||||
t.Errorf("%s: expected error", tc.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -53,23 +53,21 @@ func NewServer(ctx context.Context, config *ServerConfig) (*Inbound, error) {
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
user := &protocol.MemoryUser{
|
udpCodec, err := NewUDPServerCodec(method, psk, 500*time.Second)
|
||||||
Email: config.Email,
|
|
||||||
Level: uint32(config.Level),
|
|
||||||
}
|
|
||||||
|
|
||||||
udpCodec, err := NewUDPServerCodec(method, psk, user, 500*time.Second)
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
v := core.MustFromContext(ctx)
|
v := core.MustFromContext(ctx)
|
||||||
return &Inbound{
|
return &Inbound{
|
||||||
networks: networks,
|
networks: networks,
|
||||||
method: method,
|
method: method,
|
||||||
psk: psk,
|
psk: psk,
|
||||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||||
user: user,
|
user: &protocol.MemoryUser{
|
||||||
|
Email: config.Email,
|
||||||
|
Level: uint32(config.Level),
|
||||||
|
},
|
||||||
udpCodec: udpCodec,
|
udpCodec: udpCodec,
|
||||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||||
}, nil
|
}, nil
|
||||||
@@ -157,12 +155,20 @@ func (i *Inbound) processUDP(ctx context.Context, conn stat.Connection, dispatch
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, b := range mb {
|
for _, b := range mb {
|
||||||
sessionItem, decoded, err := i.udpCodec.DecodePacket(b.Bytes())
|
decoded, err := i.udpCodec.DecodePacket(b.Bytes())
|
||||||
b.Release()
|
b.Release()
|
||||||
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
||||||
continue
|
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()
|
link := sessionItem.link.Load()
|
||||||
if link != nil {
|
if link != nil {
|
||||||
sessionItem.UpdateConn(conn)
|
sessionItem.UpdateConn(conn)
|
||||||
|
|||||||
@@ -2,6 +2,8 @@ package shadowsocks_2022
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"crypto/cipher"
|
||||||
|
"encoding/binary"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
@@ -32,15 +34,16 @@ func init() {
|
|||||||
|
|
||||||
type MultiUserInbound struct {
|
type MultiUserInbound struct {
|
||||||
sync.Mutex
|
sync.Mutex
|
||||||
networks []net.Network
|
networks []net.Network
|
||||||
method *CipherMethod
|
method *CipherMethod
|
||||||
masterPSK []byte
|
masterPSK []byte
|
||||||
usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]
|
usersByHash *utils.TypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser]
|
||||||
usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser]
|
usersByEmail *utils.TypedSyncMap[string, *protocol.MemoryUser]
|
||||||
userCount atomic.Int64
|
userCount atomic.Int64
|
||||||
saltFilter *antireplay.ReplayFilter[[32]byte]
|
saltFilter *antireplay.ReplayFilter[[32]byte]
|
||||||
udpCodec *UDPMultiServerCodec
|
udpSessions *UDPSessionManager
|
||||||
policyManager policy.Manager
|
udpMasterCipher cipher.Block
|
||||||
|
policyManager policy.Manager
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiUserInbound, error) {
|
func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiUserInbound, error) {
|
||||||
@@ -65,21 +68,22 @@ func NewMultiServer(ctx context.Context, config *MultiUserServerConfig) (*MultiU
|
|||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
udpCodec, err := NewUDPMultiServerCodec(method, masterPSK, 500*time.Second)
|
masterBlock, err := method.NewBlock(masterPSK)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
v := core.MustFromContext(ctx)
|
v := core.MustFromContext(ctx)
|
||||||
i := &MultiUserInbound{
|
i := &MultiUserInbound{
|
||||||
networks: networks,
|
networks: networks,
|
||||||
method: method,
|
method: method,
|
||||||
masterPSK: masterPSK,
|
masterPSK: masterPSK,
|
||||||
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
|
usersByHash: utils.NewTypedSyncMap[[AESBlockSize]byte, *protocol.MemoryUser](),
|
||||||
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
|
usersByEmail: utils.NewTypedSyncMap[string, *protocol.MemoryUser](),
|
||||||
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
saltFilter: antireplay.NewMapFilter[[32]byte](60),
|
||||||
udpCodec: udpCodec,
|
udpSessions: NewUDPSessionManager(500 * time.Second),
|
||||||
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
udpMasterCipher: masterBlock,
|
||||||
|
policyManager: v.GetFeature(policy.ManagerType()).(policy.Manager),
|
||||||
}
|
}
|
||||||
|
|
||||||
for idx, user := range config.Users {
|
for idx, user := range config.Users {
|
||||||
@@ -277,26 +281,68 @@ func (i *MultiUserInbound) processUDP(ctx context.Context, conn stat.Connection,
|
|||||||
}
|
}
|
||||||
|
|
||||||
for _, b := range mb {
|
for _, b := range mb {
|
||||||
sessionItem, decoded, user, err := i.udpCodec.DecodePacket(b.Bytes(), func(hash [AESBlockSize]byte) (*protocol.MemoryUser, []byte, bool) {
|
// In multi-user UDP:
|
||||||
u, ok := i.usersByHash.Load(hash)
|
// Packet header is 16 bytes: Encrypted(SessionID + PacketID)
|
||||||
if !ok {
|
// Followed by 16 bytes EIH
|
||||||
return nil, nil, false
|
packetBytes := b.Bytes()
|
||||||
}
|
if len(packetBytes) < 32+1+8+2 {
|
||||||
return u, u.Account.(*MemoryAccount).Key, true
|
b.Release()
|
||||||
})
|
|
||||||
b.Release()
|
|
||||||
if err != nil || decoded.HeaderType != HeaderTypeClient {
|
|
||||||
continue
|
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)
|
||||||
|
if !ok {
|
||||||
|
b.Release()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
currentUser = user
|
||||||
|
userPSK = user.Account.(*MemoryAccount).Key
|
||||||
|
}
|
||||||
|
|
||||||
|
decoded, err := sessionItem.DecryptAESPayload(i.method, userPSK, sessionID, packetID, rawHeader[:], packetBytes[32:])
|
||||||
|
b.Release()
|
||||||
|
if err != nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
sessionItem.Lock()
|
||||||
|
if sessionItem.User == nil {
|
||||||
|
sessionItem.User = currentUser
|
||||||
|
sessionItem.UserPSK = userPSK
|
||||||
|
}
|
||||||
|
sessionItem.Unlock()
|
||||||
|
|
||||||
link := sessionItem.link.Load()
|
link := sessionItem.link.Load()
|
||||||
if link != nil {
|
if link != nil {
|
||||||
sessionItem.UpdateConn(conn)
|
sessionItem.UpdateConn(conn)
|
||||||
} else {
|
} else {
|
||||||
userPSK := user.Account.(*MemoryAccount).Key
|
|
||||||
var err error
|
var err error
|
||||||
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
|
link, err = sessionItem.EnsureLink(ctx, conn, decoded.Destination, dispatcher, i.policyManager, func(replyDest net.Destination, payload []byte) ([]byte, error) {
|
||||||
return i.udpCodec.EncodeServerPacket(decoded.SessionID, userPSK, replyDest, payload)
|
return i.encodeServerUDPPacket(sessionID, userPSK, replyDest, payload)
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
continue
|
continue
|
||||||
@@ -310,3 +356,7 @@ 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,14 +243,16 @@ func (i *RelayInbound) processUDP(ctx context.Context, conn stat.Connection, dis
|
|||||||
dest.Network = net.Network_UDP
|
dest.Network = net.Network_UDP
|
||||||
|
|
||||||
sessionItem := i.udpSessions.GetOrCreate(sessionID)
|
sessionItem := i.udpSessions.GetOrCreate(sessionID)
|
||||||
sessionItem.Lock()
|
|
||||||
if sessionItem.User == nil {
|
if sessionItem.User == nil {
|
||||||
sessionItem.User = &protocol.MemoryUser{
|
sessionItem.Lock()
|
||||||
Email: targetDest.email,
|
if sessionItem.User == nil {
|
||||||
Level: targetDest.level,
|
sessionItem.User = &protocol.MemoryUser{
|
||||||
|
Email: targetDest.email,
|
||||||
|
Level: targetDest.level,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
sessionItem.Unlock()
|
||||||
}
|
}
|
||||||
sessionItem.Unlock()
|
|
||||||
link := sessionItem.link.Load()
|
link := sessionItem.link.Load()
|
||||||
if link != nil {
|
if link != nil {
|
||||||
sessionItem.UpdateConn(conn)
|
sessionItem.UpdateConn(conn)
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ type Outbound struct {
|
|||||||
method *CipherMethod
|
method *CipherMethod
|
||||||
pskList [][]byte
|
pskList [][]byte
|
||||||
finalPSK []byte
|
finalPSK []byte
|
||||||
udpCodec *UDPClientCodec
|
udpCodec *UDPPacketCodec
|
||||||
policyManager policy.Manager
|
policyManager policy.Manager
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,9 +50,9 @@ func NewClient(ctx context.Context, config *ClientConfig) (*Outbound, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
finalPSK := pskList[len(pskList)-1]
|
finalPSK := pskList[len(pskList)-1]
|
||||||
udpCodec, err := NewUDPClientCodec(method, pskList)
|
udpCodec, err := NewUDPPacketCodec(method, pskList)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, errors.New("failed to create udp client codec").Base(err)
|
return nil, errors.New("failed to create udp packet codec").Base(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
v := core.MustFromContext(ctx)
|
v := core.MustFromContext(ctx)
|
||||||
|
|||||||
+143
-288
@@ -7,78 +7,33 @@ import (
|
|||||||
"io"
|
"io"
|
||||||
"math"
|
"math"
|
||||||
mrand "math/rand/v2"
|
mrand "math/rand/v2"
|
||||||
"sync"
|
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/buf"
|
"github.com/xtls/xray-core/common/buf"
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/net"
|
"github.com/xtls/xray-core/common/net"
|
||||||
"github.com/xtls/xray-core/common/protocol"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type UDPClientCodec struct {
|
type UDPCodec struct {
|
||||||
method *CipherMethod
|
method *CipherMethod
|
||||||
pskList [][]byte
|
pskList [][]byte
|
||||||
psk []byte
|
psk []byte
|
||||||
blockCipher cipher.Block
|
blockCipher cipher.Block
|
||||||
blockCiphers []cipher.Block
|
blockCiphers []cipher.Block
|
||||||
chachaCipher cipher.AEAD
|
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
|
sessions *UDPSessionManager
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewUDPServerCodec(method *CipherMethod, psk []byte, user *protocol.MemoryUser, sessionTimeout time.Duration) (*UDPServerCodec, error) {
|
type (
|
||||||
c := &UDPServerCodec{
|
UDPPacketCodec = UDPCodec
|
||||||
method: method,
|
UDPServerCodec = UDPCodec
|
||||||
psk: psk,
|
)
|
||||||
user: user,
|
|
||||||
sessions: NewUDPSessionManager(sessionTimeout),
|
func newUDPCodec(method *CipherMethod, psk []byte) (*UDPCodec, error) {
|
||||||
|
c := &UDPCodec{
|
||||||
|
method: method,
|
||||||
|
psk: psk,
|
||||||
}
|
}
|
||||||
var err error
|
var err error
|
||||||
if method.IsChaCha {
|
if method.IsChaCha {
|
||||||
@@ -92,129 +47,46 @@ func NewUDPServerCodec(method *CipherMethod, psk []byte, user *protocol.MemoryUs
|
|||||||
return c, nil
|
return c, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *UDPServerCodec) Sessions() *UDPSessionManager {
|
func NewUDPPacketCodec(method *CipherMethod, pskList [][]byte) (*UDPCodec, error) {
|
||||||
return c.sessions
|
if method.IsChaCha && len(pskList) > 1 {
|
||||||
}
|
return nil, errors.New("multi-key is not supported for chacha20-poly1305")
|
||||||
|
|
||||||
func (c *UDPServerCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
|
||||||
if c.sessions == nil {
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
return c.sessions.Get(sessionID)
|
finalPSK := pskList[len(pskList)-1]
|
||||||
}
|
c, err := newUDPCodec(method, finalPSK)
|
||||||
|
|
||||||
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 {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
return &UDPMultiServerCodec{
|
c.pskList = pskList
|
||||||
method: method,
|
if len(pskList) > 1 {
|
||||||
masterPSK: masterPSK,
|
c.blockCiphers = make([]cipher.Block, len(pskList))
|
||||||
masterBlock: masterBlock,
|
for i, psk := range pskList {
|
||||||
sessions: NewUDPSessionManager(sessionTimeout),
|
c.blockCiphers[i], err = method.NewBlock(psk)
|
||||||
}, nil
|
if err != nil {
|
||||||
}
|
return nil, err
|
||||||
|
|
||||||
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
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
return c, nil
|
||||||
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) {
|
func NewUDPServerCodec(method *CipherMethod, psk []byte, sessionTimeout time.Duration) (*UDPCodec, error) {
|
||||||
return c.sessions.EncodeServerPacket(c.method, userPSK, clientSessionID, dest, payload)
|
c, err := newUDPCodec(method, psk)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
c.sessions = NewUDPSessionManager(sessionTimeout)
|
||||||
|
return c, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *UDPCodec) Sessions() *UDPSessionManager {
|
||||||
|
return c.sessions
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *UDPCodec) GetSession(sessionID uint64) *ServerUDPSession {
|
||||||
|
if c.sessions == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return c.sessions.GetOrCreate(sessionID)
|
||||||
}
|
}
|
||||||
|
|
||||||
type DecodedUDPPacket struct {
|
type DecodedUDPPacket struct {
|
||||||
@@ -321,42 +193,44 @@ func parsePlainUDPPacket(sessionID, packetID uint64, bodyPlain []byte) (DecodedU
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUDPPacket, error) {
|
func (c *UDPCodec) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
||||||
if len(data) < PacketMinimalHeaderSize {
|
if len(data) < PacketMinimalHeaderSize {
|
||||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.method.IsChaCha {
|
if c.method.IsChaCha {
|
||||||
if len(data) < PacketNonceSize+AEADTagSize {
|
if len(data) < PacketNonceSize+AEADTagSize {
|
||||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||||
}
|
}
|
||||||
nonce := data[:PacketNonceSize]
|
nonce := data[:PacketNonceSize]
|
||||||
ciphertext := data[PacketNonceSize:]
|
ciphertext := data[PacketNonceSize:]
|
||||||
plain, err := c.chachaCipher.Open(nil, nonce, ciphertext, nil)
|
plain, err := c.chachaCipher.Open(nil, nonce, ciphertext, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
return DecodedUDPPacket{}, errors.New("failed to decrypt chacha udp packet").Base(err)
|
||||||
}
|
}
|
||||||
if len(plain) < 16+1+8+2 {
|
if len(plain) < 16+1+8+2 {
|
||||||
return nil, DecodedUDPPacket{}, ErrPacketTooShort
|
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||||
}
|
}
|
||||||
|
|
||||||
sessionID := binary.BigEndian.Uint64(plain[:8])
|
sessionID := binary.BigEndian.Uint64(plain[:8])
|
||||||
packetID := binary.BigEndian.Uint64(plain[8:16])
|
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:])
|
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, DecodedUDPPacket{}, err
|
return DecodedUDPPacket{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if decoded.HeaderType != HeaderTypeClient {
|
if decoded.HeaderType != HeaderTypeClient {
|
||||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||||
}
|
}
|
||||||
|
|
||||||
sessionItem := c.sessions.GetOrCreate(sessionID)
|
sessionItem.AddPacketID(packetID)
|
||||||
if !sessionItem.Commit(packetID, nil, c.user, c.psk) {
|
return decoded, nil
|
||||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
|
||||||
}
|
|
||||||
return sessionItem, decoded, nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// AES mode
|
// AES mode
|
||||||
@@ -365,48 +239,49 @@ func (c *UDPServerCodec) DecodePacket(data []byte) (*ServerUDPSession, DecodedUD
|
|||||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||||
|
|
||||||
sessionItem := c.sessions.Get(sessionID)
|
sessionItem := c.sessions.GetOrCreate(sessionID)
|
||||||
var bodyAead cipher.AEAD
|
if !sessionItem.CheckPacketID(packetID) {
|
||||||
if sessionItem != nil {
|
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||||
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 {
|
if bodyAead == nil {
|
||||||
bodyKey := DeriveSessionSubKey(c.psk, rawHeader[:8], c.method.KeySaltLength)
|
bodyKey := DeriveSessionSubKey(psk, rawHeader[:8], method.KeySaltLength)
|
||||||
var err error
|
var err error
|
||||||
bodyAead, err = c.method.NewAEAD(bodyKey)
|
bodyAead, err = method.NewAEAD(bodyKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, DecodedUDPPacket{}, err
|
return DecodedUDPPacket{}, err
|
||||||
}
|
}
|
||||||
|
isNewCipher = true
|
||||||
}
|
}
|
||||||
|
|
||||||
bodyNonce := rawHeader[4:16]
|
bodyNonce := rawHeader[4:16]
|
||||||
bodyCipher := data[16:]
|
|
||||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
|
decoded, err := parsePlainUDPPacket(sessionID, packetID, bodyPlain)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, DecodedUDPPacket{}, err
|
return DecodedUDPPacket{}, err
|
||||||
}
|
|
||||||
if decoded.HeaderType != HeaderTypeClient {
|
|
||||||
return nil, DecodedUDPPacket{}, ErrBadHeaderType
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if sessionItem == nil {
|
if decoded.HeaderType != HeaderTypeClient {
|
||||||
sessionItem = c.sessions.GetOrCreate(sessionID)
|
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||||
}
|
}
|
||||||
if !sessionItem.Commit(packetID, bodyAead, c.user, c.psk) {
|
|
||||||
return nil, DecodedUDPPacket{}, ErrPacketIdNotUnique
|
s.AddPacketID(packetID)
|
||||||
|
|
||||||
|
if isNewCipher {
|
||||||
|
s.clientBodyCipher = bodyAead
|
||||||
}
|
}
|
||||||
return sessionItem, decoded, nil
|
|
||||||
|
return decoded, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error {
|
func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) error {
|
||||||
@@ -428,9 +303,6 @@ func (s *ServerUDPSession) EnsureServerState(method *CipherMethod, psk []byte) e
|
|||||||
if method.IsChaCha {
|
if method.IsChaCha {
|
||||||
var err error
|
var err error
|
||||||
s.serverChaCha, err = method.NewUDPCipher(psk)
|
s.serverChaCha, err = method.NewUDPCipher(psk)
|
||||||
if err != nil {
|
|
||||||
s.ServerSessionID = 0
|
|
||||||
}
|
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -515,12 +387,11 @@ func (s *ServerUDPSession) EncodeServerPacket(method *CipherMethod, clientSessio
|
|||||||
return res, nil
|
return res, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *UDPServerCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
func (c *UDPCodec) EncodeServerPacket(clientSessionID uint64, dest net.Destination, payload []byte) ([]byte, error) {
|
||||||
return c.sessions.EncodeServerPacket(c.method, c.psk, clientSessionID, dest, payload)
|
return c.sessions.EncodeServerPacket(c.method, c.psk, clientSessionID, dest, payload)
|
||||||
}
|
}
|
||||||
|
|
||||||
type serverSessionState struct {
|
type serverSessionState struct {
|
||||||
sync.Mutex
|
|
||||||
sessionID uint64
|
sessionID uint64
|
||||||
window *SlidingWindow
|
window *SlidingWindow
|
||||||
cipher cipher.AEAD
|
cipher cipher.AEAD
|
||||||
@@ -528,24 +399,21 @@ type serverSessionState struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (st *serverSessionState) check(packetID uint64) bool {
|
func (st *serverSessionState) check(packetID uint64) bool {
|
||||||
st.Lock()
|
if st.window == nil {
|
||||||
defer st.Unlock()
|
st.window = new(SlidingWindow)
|
||||||
|
}
|
||||||
return st.window.Check(packetID)
|
return st.window.Check(packetID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (st *serverSessionState) commit(packetID uint64, now int64) bool {
|
func (st *serverSessionState) add(packetID uint64) {
|
||||||
st.Lock()
|
if st.window == nil {
|
||||||
defer st.Unlock()
|
st.window = new(SlidingWindow)
|
||||||
if !st.window.CheckAndAdd(packetID) {
|
|
||||||
return false
|
|
||||||
}
|
}
|
||||||
st.lastSeen.Store(now)
|
st.window.Add(packetID)
|
||||||
return true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type ClientUDPSession struct {
|
type ClientUDPSession struct {
|
||||||
mu sync.Mutex
|
codec *UDPCodec
|
||||||
codec *UDPClientCodec
|
|
||||||
clientSessionID uint64
|
clientSessionID uint64
|
||||||
nextPacketID atomic.Uint64
|
nextPacketID atomic.Uint64
|
||||||
clientBodyCipher cipher.AEAD
|
clientBodyCipher cipher.AEAD
|
||||||
@@ -553,7 +421,7 @@ type ClientUDPSession struct {
|
|||||||
old atomic.Pointer[serverSessionState]
|
old atomic.Pointer[serverSessionState]
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) {
|
func (c *UDPCodec) NewClientSession() (*ClientUDPSession, error) {
|
||||||
var sessID [8]byte
|
var sessID [8]byte
|
||||||
if _, err := io.ReadFull(rand.Reader, sessID[:]); err != nil {
|
if _, err := io.ReadFull(rand.Reader, sessID[:]); err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
@@ -578,43 +446,51 @@ func (c *UDPClientCodec) NewClientSession() (*ClientUDPSession, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *ClientUDPSession) findServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
func (s *ClientUDPSession) getServerSession(sessionID uint64, now int64) (*serverSessionState, error) {
|
||||||
if cur := s.current.Load(); cur != nil && cur.sessionID == sessionID {
|
cur := s.current.Load()
|
||||||
|
if cur != nil && cur.sessionID == sessionID {
|
||||||
return cur, nil
|
return cur, nil
|
||||||
}
|
}
|
||||||
if old := s.old.Load(); old != nil {
|
|
||||||
if old.sessionID == sessionID {
|
old := s.old.Load()
|
||||||
if now-old.lastSeen.Load() > 60 {
|
if old != nil && old.sessionID == sessionID {
|
||||||
return nil, errors.New("old server session expired")
|
if now-old.lastSeen.Load() > 60 {
|
||||||
}
|
s.old.CompareAndSwap(old, nil)
|
||||||
return old, nil
|
return nil, errors.New("old server session expired")
|
||||||
}
|
|
||||||
// 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 old, nil
|
||||||
}
|
}
|
||||||
return nil, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *ClientUDPSession) transitionServerSession(sessionID uint64, cipher cipher.AEAD, now int64) (*serverSessionState, error) {
|
// New server session:
|
||||||
s.mu.Lock()
|
// Spec §3.2.4: reject newer server sessions when the last packet received from the old session is less than 1 minute old.
|
||||||
defer s.mu.Unlock()
|
if old != nil && now-old.lastSeen.Load() < 60 {
|
||||||
|
return nil, errors.New("newer server session rejected: old session is less than 1 minute old")
|
||||||
|
}
|
||||||
|
|
||||||
if st, err := s.findServerSession(sessionID, now); st != nil || err != nil {
|
var bodyAead cipher.AEAD
|
||||||
return st, err
|
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
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
newState := &serverSessionState{
|
newState := &serverSessionState{
|
||||||
sessionID: sessionID,
|
sessionID: sessionID,
|
||||||
window: new(SlidingWindow),
|
cipher: bodyAead,
|
||||||
cipher: cipher,
|
|
||||||
}
|
}
|
||||||
newState.lastSeen.Store(now)
|
newState.lastSeen.Store(now)
|
||||||
|
|
||||||
if cur := s.current.Load(); cur != nil {
|
if cur == nil {
|
||||||
s.old.Store(cur)
|
s.current.CompareAndSwap(nil, newState)
|
||||||
|
return s.current.Load(), nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
s.old.Store(cur)
|
||||||
s.current.Store(newState)
|
s.current.Store(newState)
|
||||||
return newState, nil
|
return newState, nil
|
||||||
}
|
}
|
||||||
@@ -629,7 +505,7 @@ func (s *ClientUDPSession) EncodePacket(dest net.Destination, payload []byte) (*
|
|||||||
|
|
||||||
var paddingLen int
|
var paddingLen int
|
||||||
if dest.Port == 53 && len(payload) < MaxPaddingLength {
|
if dest.Port == 53 && len(payload) < MaxPaddingLength {
|
||||||
paddingLen = mrand.IntN(MaxPaddingLength-len(payload)) + 1
|
paddingLen = mrand.IntN(MaxPaddingLength) + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
addrPortLen := AddrPortLength(dest)
|
addrPortLen := AddrPortLength(dest)
|
||||||
@@ -744,8 +620,6 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
|||||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||||
}
|
}
|
||||||
|
|
||||||
now := time.Now().Unix()
|
|
||||||
|
|
||||||
if s.codec.method.IsChaCha {
|
if s.codec.method.IsChaCha {
|
||||||
if len(data) < PacketNonceSize+AEADTagSize {
|
if len(data) < PacketNonceSize+AEADTagSize {
|
||||||
return DecodedUDPPacket{}, ErrPacketTooShort
|
return DecodedUDPPacket{}, ErrPacketTooShort
|
||||||
@@ -763,10 +637,20 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
|||||||
sessionID := binary.BigEndian.Uint64(plain[:8])
|
sessionID := binary.BigEndian.Uint64(plain[:8])
|
||||||
packetID := binary.BigEndian.Uint64(plain[8:16])
|
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:])
|
decoded, err := parsePlainUDPPacket(sessionID, packetID, plain[16:])
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return DecodedUDPPacket{}, err
|
return DecodedUDPPacket{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if decoded.HeaderType != HeaderTypeServer {
|
if decoded.HeaderType != HeaderTypeServer {
|
||||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||||
}
|
}
|
||||||
@@ -774,20 +658,8 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
|||||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||||
}
|
}
|
||||||
|
|
||||||
st, err := s.findServerSession(sessionID, now)
|
st.add(packetID)
|
||||||
if err != nil {
|
st.lastSeen.Store(now)
|
||||||
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
|
return decoded, nil
|
||||||
}
|
}
|
||||||
@@ -798,29 +670,19 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
|||||||
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
sessionID := binary.BigEndian.Uint64(rawHeader[:8])
|
||||||
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
packetID := binary.BigEndian.Uint64(rawHeader[8:16])
|
||||||
|
|
||||||
st, err := s.findServerSession(sessionID, now)
|
now := time.Now().Unix()
|
||||||
|
st, err := s.getServerSession(sessionID, now)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return DecodedUDPPacket{}, err
|
return DecodedUDPPacket{}, err
|
||||||
}
|
}
|
||||||
|
if !st.check(packetID) {
|
||||||
var bodyAead cipher.AEAD
|
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
||||||
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]
|
bodyNonce := rawHeader[4:16]
|
||||||
bodyPlain, err := bodyAead.Open(nil, bodyNonce, data[16:], nil)
|
bodyCipher := data[16:]
|
||||||
|
bodyPlain, err := bodyAead.Open(nil, bodyNonce, bodyCipher, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
return DecodedUDPPacket{}, errors.New("failed to decrypt aes udp body").Base(err)
|
||||||
}
|
}
|
||||||
@@ -829,6 +691,7 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return DecodedUDPPacket{}, err
|
return DecodedUDPPacket{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
if decoded.HeaderType != HeaderTypeServer {
|
if decoded.HeaderType != HeaderTypeServer {
|
||||||
return DecodedUDPPacket{}, ErrBadHeaderType
|
return DecodedUDPPacket{}, ErrBadHeaderType
|
||||||
}
|
}
|
||||||
@@ -836,16 +699,8 @@ func (s *ClientUDPSession) DecodePacket(data []byte) (DecodedUDPPacket, error) {
|
|||||||
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
return DecodedUDPPacket{}, errors.New("client session ID mismatch")
|
||||||
}
|
}
|
||||||
|
|
||||||
if st == nil {
|
st.add(packetID)
|
||||||
st, err = s.transitionServerSession(sessionID, bodyAead, now)
|
st.lastSeen.Store(now)
|
||||||
if err != nil {
|
|
||||||
return DecodedUDPPacket{}, err
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !st.commit(packetID, now) {
|
|
||||||
return DecodedUDPPacket{}, ErrPacketIdNotUnique
|
|
||||||
}
|
|
||||||
|
|
||||||
return decoded, nil
|
return decoded, nil
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -191,7 +191,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
|||||||
// Verify downstream destination can decode both packets
|
// Verify downstream destination can decode both packets
|
||||||
method, err := GetCipherMethod(MethodAES128GCM)
|
method, err := GetCipherMethod(MethodAES128GCM)
|
||||||
common.Must(err)
|
common.Must(err)
|
||||||
destCodec, err := NewUDPServerCodec(method, destKey, nil, 300*time.Second)
|
destCodec, err := NewUDPServerCodec(method, destKey, 300*time.Second)
|
||||||
common.Must(err)
|
common.Must(err)
|
||||||
|
|
||||||
mu.Lock()
|
mu.Lock()
|
||||||
@@ -202,8 +202,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
|||||||
t.Fatalf("expected 2 received packets at destination, got %d", len(pkts))
|
t.Fatalf("expected 2 received packets at destination, got %d", len(pkts))
|
||||||
}
|
}
|
||||||
|
|
||||||
dec1, dec2 := DecodedUDPPacket{}, DecodedUDPPacket{}
|
dec1, err := destCodec.DecodePacket(pkts[0])
|
||||||
_, dec1, err = destCodec.DecodePacket(pkts[0])
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("dest failed to decode packet 1: %v", err)
|
t.Fatalf("dest failed to decode packet 1: %v", err)
|
||||||
}
|
}
|
||||||
@@ -211,7 +210,7 @@ func TestRelayUDPSessionStabilityAndDispatch(t *testing.T) {
|
|||||||
t.Fatalf("dec1 mismatch: sess=%x, pktID=%d, payload=%s", dec1.SessionID, dec1.PacketID, string(dec1.Payload))
|
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 {
|
if err != nil {
|
||||||
t.Fatalf("dest failed to decode packet 2: %v", err)
|
t.Fatalf("dest failed to decode packet 2: %v", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -100,27 +100,19 @@ type ServerUDPSession struct {
|
|||||||
func (s *ServerUDPSession) CheckPacketID(packetID uint64) bool {
|
func (s *ServerUDPSession) CheckPacketID(packetID uint64) bool {
|
||||||
s.Lock()
|
s.Lock()
|
||||||
defer s.Unlock()
|
defer s.Unlock()
|
||||||
|
if s.Window == nil {
|
||||||
|
s.Window = new(SlidingWindow)
|
||||||
|
}
|
||||||
return s.Window.Check(packetID)
|
return s.Window.Check(packetID)
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *ServerUDPSession) Commit(packetID uint64, bodyAead cipher.AEAD, user *protocol.MemoryUser, userPSK []byte) bool {
|
func (s *ServerUDPSession) AddPacketID(packetID uint64) {
|
||||||
s.Lock()
|
s.Lock()
|
||||||
defer s.Unlock()
|
defer s.Unlock()
|
||||||
if s.User != nil && user != nil && s.User != user {
|
if s.Window == nil {
|
||||||
return false
|
s.Window = new(SlidingWindow)
|
||||||
}
|
}
|
||||||
if !s.Window.CheckAndAdd(packetID) {
|
s.Window.Add(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 {
|
type UDPSessionManager struct {
|
||||||
@@ -136,13 +128,6 @@ 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 {
|
func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
||||||
now := time.Now().Unix()
|
now := time.Now().Unix()
|
||||||
if s, ok := m.sessions.Load(sessionID); ok {
|
if s, ok := m.sessions.Load(sessionID); ok {
|
||||||
@@ -152,7 +137,6 @@ func (m *UDPSessionManager) GetOrCreate(sessionID uint64) *ServerUDPSession {
|
|||||||
|
|
||||||
s := &ServerUDPSession{
|
s := &ServerUDPSession{
|
||||||
SessionID: sessionID,
|
SessionID: sessionID,
|
||||||
Window: new(SlidingWindow),
|
|
||||||
manager: m,
|
manager: m,
|
||||||
}
|
}
|
||||||
s.LastActive.Store(now)
|
s.LastActive.Store(now)
|
||||||
|
|||||||
@@ -63,16 +63,10 @@ func (s *ServerUDPSession) EnsureLink(
|
|||||||
|
|
||||||
s.currentConn.Store(conn)
|
s.currentConn.Store(conn)
|
||||||
|
|
||||||
// UDP Session might travel across multiple connections
|
sessCtx, cancel := context.WithCancel(ctx)
|
||||||
// don't bind its lifetime to a parent context
|
|
||||||
sessCtx, cancel := context.WithCancel(context.WithoutCancel(ctx))
|
|
||||||
inbound := session.InboundFromContext(sessCtx)
|
inbound := session.InboundFromContext(sessCtx)
|
||||||
if inbound != nil {
|
if inbound != nil && s.User != nil {
|
||||||
newInbound := *inbound
|
inbound.User = s.User
|
||||||
if s.User != nil {
|
|
||||||
newInbound.User = s.User
|
|
||||||
}
|
|
||||||
sessCtx = session.ContextWithInbound(sessCtx, &newInbound)
|
|
||||||
}
|
}
|
||||||
var email string
|
var email string
|
||||||
var level uint32
|
var level uint32
|
||||||
|
|||||||
@@ -265,7 +265,7 @@ func TestUDPCodec(t *testing.T) {
|
|||||||
|
|
||||||
clientCodec, err := NewUDPPacketCodec(method, [][]byte{psk})
|
clientCodec, err := NewUDPPacketCodec(method, [][]byte{psk})
|
||||||
common.Must(err)
|
common.Must(err)
|
||||||
serverCodec, err := NewUDPServerCodec(method, psk, nil, time.Minute)
|
serverCodec, err := NewUDPServerCodec(method, psk, time.Minute)
|
||||||
common.Must(err)
|
common.Must(err)
|
||||||
|
|
||||||
session, err := clientCodec.NewClientSession()
|
session, err := clientCodec.NewClientSession()
|
||||||
@@ -277,7 +277,7 @@ func TestUDPCodec(t *testing.T) {
|
|||||||
rawCopy := make([]byte, pktBuf.Len())
|
rawCopy := make([]byte, pktBuf.Len())
|
||||||
copy(rawCopy, pktBuf.Bytes())
|
copy(rawCopy, pktBuf.Bytes())
|
||||||
|
|
||||||
_, decoded, err := serverCodec.DecodePacket(pktBuf.Bytes())
|
decoded, err := serverCodec.DecodePacket(pktBuf.Bytes())
|
||||||
common.Must(err)
|
common.Must(err)
|
||||||
|
|
||||||
if decoded.HeaderType != HeaderTypeClient {
|
if decoded.HeaderType != HeaderTypeClient {
|
||||||
@@ -291,7 +291,7 @@ func TestUDPCodec(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Replay same packet wire bytes should fail with ErrPacketIdNotUnique
|
// Replay same packet wire bytes should fail with ErrPacketIdNotUnique
|
||||||
_, _, err = serverCodec.DecodePacket(rawCopy)
|
_, err = serverCodec.DecodePacket(rawCopy)
|
||||||
if err != ErrPacketIdNotUnique {
|
if err != ErrPacketIdNotUnique {
|
||||||
t.Fatalf("expected ErrPacketIdNotUnique on replay, got: %v", err)
|
t.Fatalf("expected ErrPacketIdNotUnique on replay, got: %v", err)
|
||||||
}
|
}
|
||||||
@@ -427,7 +427,7 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
|
|||||||
|
|
||||||
clientCodec, err := NewUDPPacketCodec(method, [][]byte{rawKey})
|
clientCodec, err := NewUDPPacketCodec(method, [][]byte{rawKey})
|
||||||
common.Must(err)
|
common.Must(err)
|
||||||
serverCodec, err := NewUDPServerCodec(method, rawKey, nil, time.Minute)
|
serverCodec, err := NewUDPServerCodec(method, rawKey, time.Minute)
|
||||||
common.Must(err)
|
common.Must(err)
|
||||||
|
|
||||||
session, err := clientCodec.NewClientSession()
|
session, err := clientCodec.NewClientSession()
|
||||||
@@ -448,9 +448,9 @@ func TestClientUDPSessionMultiDestination(t *testing.T) {
|
|||||||
defer pkt2.Release()
|
defer pkt2.Release()
|
||||||
|
|
||||||
// Server decodes both
|
// Server decodes both
|
||||||
_, dec1, err := serverCodec.DecodePacket(pkt1.Bytes())
|
dec1, err := serverCodec.DecodePacket(pkt1.Bytes())
|
||||||
common.Must(err)
|
common.Must(err)
|
||||||
_, dec2, err := serverCodec.DecodePacket(pkt2.Bytes())
|
dec2, err := serverCodec.DecodePacket(pkt2.Bytes())
|
||||||
common.Must(err)
|
common.Must(err)
|
||||||
|
|
||||||
if dec1.SessionID != session.ClientSessionID() || dec2.SessionID != session.ClientSessionID() {
|
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)
|
addrPortLen := AddrPortLength(dest)
|
||||||
varHeaderLen := addrPortLen + 2 + paddingLen + payloadLen
|
varHeaderLen := addrPortLen + 2 + paddingLen + payloadLen
|
||||||
|
|
||||||
totalHandshakeLen := int32(method.KeySaltLength + (len(pskList)-1)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
totalHandshakeLen := int32(method.KeySaltLength + len(pskList)*AESBlockSize + RequestHeaderFixedChunkLength + AEADTagSize + varHeaderLen + AEADTagSize)
|
||||||
handshakeBuf := buf.NewWithSize(totalHandshakeLen)
|
handshakeBuf := buf.NewWithSize(totalHandshakeLen)
|
||||||
defer handshakeBuf.Release()
|
defer handshakeBuf.Release()
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"net"
|
"net"
|
||||||
"sync"
|
"sync"
|
||||||
|
|
||||||
"github.com/google/uuid"
|
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -50,18 +49,3 @@ func (updater *InterfaceUpdater) Update() {
|
|||||||
updater.iface = got
|
updater.iface = got
|
||||||
errors.LogInfo(context.Background(), "[tun] update interface ", got.Name, " ", got.Index)
|
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
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
package tun
|
||||||
|
|
||||||
|
import (
|
||||||
|
"github.com/google/uuid"
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
)
|
||||||
|
|
||||||
|
// ParseGUID parses a canonical textual GUID, as in
|
||||||
|
// "00000000-0000-0000-0000-000000000000", into the 16 bytes it denotes.
|
||||||
|
// The form is all that is accepted, not the other ones uuid.Parse takes,
|
||||||
|
// such as one without hyphens; the length check is what rules those out.
|
||||||
|
func ParseGUID(s string) ([16]byte, error) {
|
||||||
|
if len(s) != 36 {
|
||||||
|
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx")
|
||||||
|
}
|
||||||
|
id, err := uuid.Parse(s)
|
||||||
|
if err != nil {
|
||||||
|
return [16]byte{}, errors.New("invalid guid: ", s, ", want xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx").Base(err)
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
package tun_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/proxy/tun"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestParseGUID(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
guid string
|
||||||
|
raw [16]byte
|
||||||
|
}{
|
||||||
|
{"00000000-0000-0000-0000-000000000000", [16]byte{}},
|
||||||
|
{"00010203-0405-0607-0809-0a0b0c0d0e0f", [16]byte{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}},
|
||||||
|
{"6ba7b810-9dad-11d1-80b4-00c04fd430c8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
|
||||||
|
{"6BA7B810-9DAD-11D1-80B4-00C04FD430C8", [16]byte{0x6b, 0xa7, 0xb8, 0x10, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8}},
|
||||||
|
{"ffffffff-ffff-ffff-ffff-ffffffffffff", [16]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}},
|
||||||
|
} {
|
||||||
|
raw, err := tun.ParseGUID(c.guid)
|
||||||
|
if err != nil {
|
||||||
|
t.Errorf("ParseGUID(%q) failed: %v", c.guid, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if raw != c.raw {
|
||||||
|
t.Errorf("ParseGUID(%q) = %x, want %x", c.guid, raw, c.raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseGUIDInvalid(t *testing.T) {
|
||||||
|
for _, guid := range []string{
|
||||||
|
"",
|
||||||
|
" ",
|
||||||
|
"xray0",
|
||||||
|
// right characters, wrong places of the hyphens
|
||||||
|
"6ba7b8109-dad-11d1-80b4-00c04fd430c8",
|
||||||
|
"6ba7b810-9dad-11d1-80b4-00c04fd430c",
|
||||||
|
"6ba7b810-9dad-11d1-80b4-00c04fd430c88",
|
||||||
|
"6ba7b810-9dad-11d1-80b4_00c04fd430c8",
|
||||||
|
// not hexadecimal
|
||||||
|
"6ba7b81g-9dad-11d1-80b4-00c04fd430c8",
|
||||||
|
"6ba7b810-9dad-11d1-80b4-00c04fd430cg",
|
||||||
|
// forms other than the canonical one
|
||||||
|
"6ba7b8109dad11d180b400c04fd430c8",
|
||||||
|
"{6ba7b810-9dad-11d1-80b4-00c04fd430c8}",
|
||||||
|
"urn:uuid:6ba7b810-9dad-11d1-80b4-00c04fd430c8",
|
||||||
|
"6ba7b810-9dad-11d1-80b4-00c04fd430c8 ",
|
||||||
|
} {
|
||||||
|
if raw, err := tun.ParseGUID(guid); err == nil {
|
||||||
|
t.Errorf("ParseGUID(%q) = %x, want an error", guid, raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package tun
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/md5"
|
||||||
|
"testing"
|
||||||
|
"unsafe"
|
||||||
|
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestAdapterGUID(t *testing.T) {
|
||||||
|
// a configured GUID has to be the adapter GUID the text names: the groups
|
||||||
|
// are field values, not the bytes of the text in order
|
||||||
|
guid, err := adapterGUID("xray0", "01020304-0506-0708-090a-0b0c0d0e0f10")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := windows.GUID{
|
||||||
|
Data1: 0x01020304,
|
||||||
|
Data2: 0x0506,
|
||||||
|
Data3: 0x0708,
|
||||||
|
Data4: [8]byte{0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10},
|
||||||
|
}
|
||||||
|
if *guid != want {
|
||||||
|
t.Errorf("adapterGUID = %+v, want %+v", *guid, want)
|
||||||
|
}
|
||||||
|
// the same struct Windows builds from that text, and the text Windows shows
|
||||||
|
// for it
|
||||||
|
if fromText, err := windows.GUIDFromString("{01020304-0506-0708-090A-0B0C0D0E0F10}"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
} else if *guid != fromText {
|
||||||
|
t.Errorf("adapterGUID = %s, want %s", guid.String(), fromText.String())
|
||||||
|
}
|
||||||
|
if got, want := guid.String(), "{01020304-0506-0708-090A-0B0C0D0E0F10}"; got != want {
|
||||||
|
t.Errorf("adapterGUID = %s, want %s", got, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// without one, the bytes of the MD5 of the name, as they always were; that
|
||||||
|
// GUID is never read back as text, so its byte order does not matter
|
||||||
|
guid, err = adapterGUID("xray0", "")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
sum := md5.Sum([]byte("xray0"))
|
||||||
|
if got := unsafe.Slice((*byte)(unsafe.Pointer(guid)), 16); string(got) != string(sum[:]) {
|
||||||
|
t.Errorf("adapterGUID = %x, want %x", got, sum)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := adapterGUID("xray0", "xray0"); err == nil {
|
||||||
|
t.Error("an invalid guid was accepted")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,390 @@
|
|||||||
|
//go:build freebsd
|
||||||
|
|
||||||
|
package tun
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"io/fs"
|
||||||
|
"net/netip"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
type probeCall struct {
|
||||||
|
inboundTag string
|
||||||
|
source string
|
||||||
|
address string
|
||||||
|
}
|
||||||
|
|
||||||
|
// stubDNSRouting replaces the routing probe for the duration of a test and
|
||||||
|
// records how it was called, so tests can assert the probe is representative.
|
||||||
|
func stubDNSRouting(t *testing.T, err error) *[]probeCall {
|
||||||
|
t.Helper()
|
||||||
|
original := verifyDNSRouting
|
||||||
|
calls := []probeCall{}
|
||||||
|
verifyDNSRouting = func(_ context.Context, inboundTag, source, address string) error {
|
||||||
|
calls = append(calls, probeCall{inboundTag, source, address})
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { verifyDNSRouting = original })
|
||||||
|
return &calls
|
||||||
|
}
|
||||||
|
|
||||||
|
// recorder installs a resolvconf stub for the duration of a test and returns
|
||||||
|
// the captured invocations, each as the arguments followed by the stdin in
|
||||||
|
// angle brackets when there was one. An empty failOn succeeds every call;
|
||||||
|
// otherwise the named subcommand fails.
|
||||||
|
func recorder(t *testing.T, failOn string) *[]string {
|
||||||
|
t.Helper()
|
||||||
|
original := resolvconfRunner
|
||||||
|
calls := []string{}
|
||||||
|
resolvconfRunner = func(stdin string, args ...string) ([]byte, error) {
|
||||||
|
call := strings.Join(args, " ")
|
||||||
|
if stdin != "" {
|
||||||
|
call += " <" + stdin + ">"
|
||||||
|
}
|
||||||
|
calls = append(calls, call)
|
||||||
|
if failOn != "" && len(args) > 0 && args[0] == failOn {
|
||||||
|
return nil, errors.New("boom")
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { resolvconfRunner = original })
|
||||||
|
return &calls
|
||||||
|
}
|
||||||
|
|
||||||
|
// files replaces the resolver files read by the applied check for the
|
||||||
|
// duration of a test. A path not in the map does not exist.
|
||||||
|
func files(t *testing.T, contents map[string]string) {
|
||||||
|
t.Helper()
|
||||||
|
original := readResolverFile
|
||||||
|
readResolverFile = func(path string) ([]byte, error) {
|
||||||
|
if data, ok := contents[path]; ok {
|
||||||
|
return []byte(data), nil
|
||||||
|
}
|
||||||
|
return nil, fs.ErrNotExist
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { readResolverFile = original })
|
||||||
|
}
|
||||||
|
|
||||||
|
// takenOver is what the libc subscriber writes once the TUN's nameserver is
|
||||||
|
// the exclusive one.
|
||||||
|
const takenOver = "# Generated by resolvconf\nnameserver 192.168.100.1\n"
|
||||||
|
|
||||||
|
// untouched is the DHCP-supplied resolv.conf that resolvconf=NO leaves in
|
||||||
|
// place.
|
||||||
|
const untouched = "# Generated by resolvconf\nnameserver 10.0.0.1\n"
|
||||||
|
|
||||||
|
func optedInTun() *FreeBSDTun {
|
||||||
|
return &FreeBSDTun{
|
||||||
|
options: &Config{
|
||||||
|
Name: "tun7",
|
||||||
|
Gateway: []string{"192.168.100.1/30"},
|
||||||
|
AutoSystemDnsToGateway: true,
|
||||||
|
},
|
||||||
|
name: "tun7",
|
||||||
|
gateway: netip.MustParsePrefix("192.168.100.1/30"),
|
||||||
|
local: netip.MustParseAddr("192.168.100.2"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func joined(calls []string) string {
|
||||||
|
return strings.Join(calls, " | ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureSystemDNSDisabledByDefault(t *testing.T) {
|
||||||
|
probes := stubDNSRouting(t, nil)
|
||||||
|
calls := recorder(t, "")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
t1.options.AutoSystemDnsToGateway = false
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if len(*calls) != 0 || len(*probes) != 0 {
|
||||||
|
t.Errorf("nothing may run when the option is off, got %q and %d probes", joined(*calls), len(*probes))
|
||||||
|
}
|
||||||
|
if t1.systemDNSSet {
|
||||||
|
t.Error("systemDNSSet must stay false when the option is off")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureSystemDNSLeavesOSDNSWhenNoRoute(t *testing.T) {
|
||||||
|
stubDNSRouting(t, errors.New("no route"))
|
||||||
|
calls := recorder(t, "")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||||
|
t.Fatal("expected an error when the probe fails")
|
||||||
|
}
|
||||||
|
if len(*calls) != 0 {
|
||||||
|
t.Errorf("resolvconf must not run when the probe fails, got %q", joined(*calls))
|
||||||
|
}
|
||||||
|
if t1.systemDNSSet {
|
||||||
|
t.Error("systemDNSSet must stay false when the probe fails")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// On FreeBSD the addresses are the other way round from Linux: the local
|
||||||
|
// address is the one after the gateway, and the gateway itself has no owner,
|
||||||
|
// so a packet to it is routed into the TUN. The probe has to carry that pair,
|
||||||
|
// and the resolver has to be pointed at the gateway.
|
||||||
|
func TestConfigureSystemDNSProbeCarriesFreeBSDPair(t *testing.T) {
|
||||||
|
probes := stubDNSRouting(t, nil)
|
||||||
|
recorder(t, "")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if len(*probes) != 1 {
|
||||||
|
t.Fatalf("expected one probe, got %d", len(*probes))
|
||||||
|
}
|
||||||
|
want := probeCall{"tun", "192.168.100.2", "192.168.100.1"}
|
||||||
|
if (*probes)[0] != want {
|
||||||
|
t.Errorf("probe = %+v, want %+v", (*probes)[0], want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureSystemDNSAppliesResolvconf(t *testing.T) {
|
||||||
|
stubDNSRouting(t, nil)
|
||||||
|
calls := recorder(t, "")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if !t1.systemDNSSet {
|
||||||
|
t.Fatal("systemDNSSet should be true after a successful takeover")
|
||||||
|
}
|
||||||
|
|
||||||
|
want := "-a tun7 -x <nameserver 192.168.100.1\n>"
|
||||||
|
if got := joined(*calls); got != want {
|
||||||
|
t.Errorf("resolvconf calls = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// resolvconf exits 0 with resolvconf=NO in resolvconf.conf, and still records
|
||||||
|
// the entry for the interface, but runs no subscriber, so success has to be
|
||||||
|
// confirmed in what the subscribers wrote.
|
||||||
|
func TestConfigureSystemDNSRefusesWhenResolvconfDidNotApply(t *testing.T) {
|
||||||
|
stubDNSRouting(t, nil)
|
||||||
|
calls := recorder(t, "")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||||
|
t.Fatal("expected an error when the nameserver did not reach a resolver")
|
||||||
|
}
|
||||||
|
if t1.systemDNSSet {
|
||||||
|
t.Error("systemDNSSet must stay false when the takeover did not take")
|
||||||
|
}
|
||||||
|
if !strings.HasSuffix(joined(*calls), "-d tun7") {
|
||||||
|
t.Errorf("expected a removal after the failed check, got %q", joined(*calls))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureSystemDNSIdempotent(t *testing.T) {
|
||||||
|
stubDNSRouting(t, nil)
|
||||||
|
calls := recorder(t, "")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
before := len(*calls)
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
if len(*calls) != before {
|
||||||
|
t.Errorf("second call must be a no-op, calls went %d -> %d", before, len(*calls))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConfigureSystemDNSAddFailureIsNotDirty(t *testing.T) {
|
||||||
|
stubDNSRouting(t, nil)
|
||||||
|
calls := recorder(t, "-a")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||||
|
t.Fatal("expected an error when resolvconf -a fails")
|
||||||
|
}
|
||||||
|
if t1.systemDNSSet || t1.systemDNSDirty {
|
||||||
|
t.Error("a failed add leaves nothing to clean up")
|
||||||
|
}
|
||||||
|
if len(*calls) != 1 {
|
||||||
|
t.Errorf("nothing else may run after a failed add, got %q", joined(*calls))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If the removal after a failed check fails too, the entry may still be
|
||||||
|
// installed, so the state has to be remembered rather than silently dropped.
|
||||||
|
func TestConfigureSystemDNSRollbackFailureKeepsDirty(t *testing.T) {
|
||||||
|
stubDNSRouting(t, nil)
|
||||||
|
recorder(t, "-d")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err == nil {
|
||||||
|
t.Fatal("expected an error when the check fails")
|
||||||
|
}
|
||||||
|
if !t1.systemDNSDirty {
|
||||||
|
t.Error("a failed removal must leave the resolver marked dirty")
|
||||||
|
}
|
||||||
|
if t1.systemDNSSet {
|
||||||
|
t.Error("systemDNSSet must stay false when the takeover did not complete")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A dirty resolver is retried before anything new is applied.
|
||||||
|
func TestConfigureSystemDNSRetriesDirtyBeforeApplying(t *testing.T) {
|
||||||
|
stubDNSRouting(t, nil)
|
||||||
|
calls := recorder(t, "")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
t1.systemDNSDirty = true
|
||||||
|
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||||
|
t.Fatalf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
got := joined(*calls)
|
||||||
|
if !strings.HasPrefix(got, "-d tun7 | -a tun7") {
|
||||||
|
t.Errorf("expected the stale removal first, got %q", got)
|
||||||
|
}
|
||||||
|
if t1.systemDNSDirty {
|
||||||
|
t.Error("a successful retry should clear the dirty flag")
|
||||||
|
}
|
||||||
|
if !t1.systemDNSSet {
|
||||||
|
t.Error("the takeover should proceed once the retry succeeds")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnsetSystemDNSRemoves(t *testing.T) {
|
||||||
|
stubDNSRouting(t, nil)
|
||||||
|
calls := recorder(t, "")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
if err := t1.ConfigureSystemDNS(context.Background(), "tun"); err != nil {
|
||||||
|
t.Fatalf("setup failed: %v", err)
|
||||||
|
}
|
||||||
|
*calls = nil
|
||||||
|
|
||||||
|
t1.unsetSystemDNS()
|
||||||
|
if t1.systemDNSSet {
|
||||||
|
t.Error("systemDNSSet should be false after unset")
|
||||||
|
}
|
||||||
|
if got := joined(*calls); got != "-d tun7" {
|
||||||
|
t.Errorf("unset calls = %q, want %q", got, "-d tun7")
|
||||||
|
}
|
||||||
|
|
||||||
|
t1.unsetSystemDNS()
|
||||||
|
if len(*calls) != 1 {
|
||||||
|
t.Errorf("unsetSystemDNS must be idempotent, got %q", joined(*calls))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUnsetSystemDNSKeepsDirtyWhenRemoveFails(t *testing.T) {
|
||||||
|
stubDNSRouting(t, nil)
|
||||||
|
calls := recorder(t, "-d")
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
|
||||||
|
t1 := optedInTun()
|
||||||
|
t1.systemDNSSet = true
|
||||||
|
|
||||||
|
t1.unsetSystemDNS()
|
||||||
|
if !t1.systemDNSDirty {
|
||||||
|
t.Error("a failed removal during unset must be remembered")
|
||||||
|
}
|
||||||
|
if got := joined(*calls); got != "-d tun7" {
|
||||||
|
t.Errorf("expected a removal attempt, got %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolvconfAppliedLibc(t *testing.T) {
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": takenOver})
|
||||||
|
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||||
|
t.Errorf("resolv.conf listing the nameserver must count as applied, got %v, %v", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolvconfAppliedNotWhenUntouched(t *testing.T) {
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": untouched})
|
||||||
|
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || ok {
|
||||||
|
t.Errorf("an unchanged resolv.conf and no resolvconf.conf must not count as applied, got %v, %v", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// With inclusive_interfaces in resolvconf.conf the exclusive marking is
|
||||||
|
// ignored and the DHCP nameservers stay listed, so the system falls back to
|
||||||
|
// them; that is the leak the option exists to close, and it must not pass.
|
||||||
|
func TestResolvconfAppliedNotWhenOthersRemain(t *testing.T) {
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.1\nnameserver 10.0.0.1\n"})
|
||||||
|
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||||
|
t.Error("another nameserver alongside the TUN's must not count as applied")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// A loopback nameserver alongside is a local resolver that resolvconf feeds
|
||||||
|
// (local_unbound with the libc subscriber left on), not a leak.
|
||||||
|
func TestResolvconfAppliedWithLoopbackAlongside(t *testing.T) {
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": "nameserver 127.0.0.1\nnameserver 192.168.100.1\n"})
|
||||||
|
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||||
|
t.Errorf("a loopback nameserver alongside must still count as applied, got %v, %v", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolvconfAppliedIgnoresPrefixMatches(t *testing.T) {
|
||||||
|
files(t, map[string]string{"/etc/resolv.conf": "nameserver 192.168.100.10\n"})
|
||||||
|
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||||
|
t.Error("192.168.100.10 must not match 192.168.100.1")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// local-unbound-setup turns the libc subscriber off and has resolvconf write
|
||||||
|
// unbound's forwarders instead; resolv.conf then stays pointed at loopback.
|
||||||
|
func TestResolvconfAppliedUnbound(t *testing.T) {
|
||||||
|
files(t, map[string]string{
|
||||||
|
"/etc/resolv.conf": "# Generated by resolvconf\nnameserver 127.0.0.1\noptions edns0\n",
|
||||||
|
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||||
|
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 192.168.100.1\n",
|
||||||
|
})
|
||||||
|
if ok, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err != nil || !ok {
|
||||||
|
t.Errorf("the nameserver in unbound's forwarders must count as applied, got %v, %v", ok, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolvconfAppliedNotWhenUnboundUntouched(t *testing.T) {
|
||||||
|
files(t, map[string]string{
|
||||||
|
"/etc/resolv.conf": "nameserver 127.0.0.1\n",
|
||||||
|
"/etc/resolvconf.conf": "libc=\"NO\"\nunbound_conf=\"/var/unbound/forward.conf\"\n",
|
||||||
|
"/var/unbound/forward.conf": "forward-zone:\n\tname: .\n\tforward-addr: 10.0.0.1\n",
|
||||||
|
})
|
||||||
|
if ok, _ := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); ok {
|
||||||
|
t.Error("unbound still forwarding to the old server must not count as applied")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestResolvconfAppliedReportsUnreadableResolvConf(t *testing.T) {
|
||||||
|
files(t, map[string]string{})
|
||||||
|
if _, err := resolvconfApplied(netip.MustParseAddr("192.168.100.1")); err == nil {
|
||||||
|
t.Error("a missing resolv.conf is an error, not a verdict")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,11 +3,7 @@
|
|||||||
package tun
|
package tun
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
"io/fs"
|
|
||||||
"net/netip"
|
"net/netip"
|
||||||
"strings"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"golang.org/x/net/route"
|
"golang.org/x/net/route"
|
||||||
@@ -152,381 +148,3 @@ func TestDefaultRouteFamilyRejectsShortAddrs(t *testing.T) {
|
|||||||
t.Fatal("message without addresses must not match")
|
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")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,204 @@
|
|||||||
|
//go:build linux && !android
|
||||||
|
|
||||||
|
package tun
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/app/dispatcher"
|
||||||
|
appdns "github.com/xtls/xray-core/app/dns"
|
||||||
|
"github.com/xtls/xray-core/app/proxyman"
|
||||||
|
_ "github.com/xtls/xray-core/app/proxyman/inbound"
|
||||||
|
_ "github.com/xtls/xray-core/app/proxyman/outbound"
|
||||||
|
"github.com/xtls/xray-core/app/router"
|
||||||
|
"github.com/xtls/xray-core/common/geodata"
|
||||||
|
"github.com/xtls/xray-core/common/net"
|
||||||
|
"github.com/xtls/xray-core/common/serial"
|
||||||
|
"github.com/xtls/xray-core/core"
|
||||||
|
proxydns "github.com/xtls/xray-core/proxy/dns"
|
||||||
|
"github.com/xtls/xray-core/proxy/freedom"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
routeTestInboundTag = "tun"
|
||||||
|
routeTestSource = "192.168.100.1"
|
||||||
|
routeTestDNSAddress = "192.168.100.2"
|
||||||
|
)
|
||||||
|
|
||||||
|
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
||||||
|
func port53Rule() *router.RoutingRule {
|
||||||
|
return &router.RoutingRule{
|
||||||
|
InboundTag: []string{routeTestInboundTag},
|
||||||
|
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
||||||
|
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
||||||
|
// that only matches because the real request carries a source.
|
||||||
|
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
||||||
|
return &router.RoutingRule{
|
||||||
|
SourceIp: []*geodata.IPRule{{
|
||||||
|
Value: &geodata.IPRule_Custom{
|
||||||
|
Custom: &geodata.CIDRRule{
|
||||||
|
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}},
|
||||||
|
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
||||||
|
// running resolver. The instance is placed in the context through the key core
|
||||||
|
// exports for tests.
|
||||||
|
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
||||||
|
t.Helper()
|
||||||
|
|
||||||
|
apps := []*serial.TypedMessage{
|
||||||
|
serial.ToTypedMessage(&dispatcher.Config{}),
|
||||||
|
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
||||||
|
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
||||||
|
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
||||||
|
}
|
||||||
|
if withDNSApp {
|
||||||
|
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
||||||
|
}
|
||||||
|
|
||||||
|
instance, err := core.New(&core.Config{
|
||||||
|
App: apps,
|
||||||
|
Outbound: []*core.OutboundHandlerConfig{
|
||||||
|
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
||||||
|
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
||||||
|
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("core.New: %v", err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { _ = instance.Close() })
|
||||||
|
|
||||||
|
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
||||||
|
}
|
||||||
|
|
||||||
|
func udpNameServer(ip []byte) []*appdns.NameServer {
|
||||||
|
return []*appdns.NameServer{{
|
||||||
|
Address: &net.Endpoint{
|
||||||
|
Network: net.Network_UDP,
|
||||||
|
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
||||||
|
Port: 53,
|
||||||
|
},
|
||||||
|
}}
|
||||||
|
}
|
||||||
|
|
||||||
|
// localNameServer is a name server pointed at "localhost", which app/dns
|
||||||
|
// resolves through the system resolver.
|
||||||
|
func localNameServer() *appdns.NameServer {
|
||||||
|
return &appdns.NameServer{
|
||||||
|
Address: &net.Endpoint{
|
||||||
|
Network: net.Network_UDP,
|
||||||
|
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
||||||
|
Port: 53,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
||||||
|
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
||||||
|
// false positive in the takeover decision itself, which is what assertions on
|
||||||
|
// the resolvectl arguments could never catch.
|
||||||
|
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
name string
|
||||||
|
withDNSApp bool
|
||||||
|
nameServers []*appdns.NameServer
|
||||||
|
rules []*router.RoutingRule
|
||||||
|
wantErr string
|
||||||
|
}{
|
||||||
|
{
|
||||||
|
name: "independent upstream reaches the dns outbound",
|
||||||
|
withDNSApp: true,
|
||||||
|
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||||
|
rules: []*router.RoutingRule{port53Rule()},
|
||||||
|
wantErr: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "no dns section falls back to the system resolver",
|
||||||
|
rules: []*router.RoutingRule{port53Rule()},
|
||||||
|
wantErr: "system resolver",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "dns section without name servers falls back too",
|
||||||
|
withDNSApp: true,
|
||||||
|
rules: []*router.RoutingRule{port53Rule()},
|
||||||
|
wantErr: "system resolver",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
// An independent upstream is not enough on its own: name servers are
|
||||||
|
// selected per domain, so a local one can still be the one chosen.
|
||||||
|
// The refusal is deliberately domain-agnostic for that reason.
|
||||||
|
name: "a local name server alongside an independent one",
|
||||||
|
withDNSApp: true,
|
||||||
|
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
||||||
|
rules: []*router.RoutingRule{port53Rule()},
|
||||||
|
wantErr: "system resolver",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "a rule on the interface address diverts the real query",
|
||||||
|
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||||
|
rules: []*router.RoutingRule{
|
||||||
|
sourceBlockRule([]byte{192, 168, 100, 1}),
|
||||||
|
port53Rule(),
|
||||||
|
},
|
||||||
|
wantErr: "does not handle DNS",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "a rule on another address does not match it",
|
||||||
|
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||||
|
rules: []*router.RoutingRule{
|
||||||
|
sourceBlockRule([]byte{10, 0, 0, 1}),
|
||||||
|
port53Rule(),
|
||||||
|
},
|
||||||
|
wantErr: "",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "no rule matches the query",
|
||||||
|
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
||||||
|
wantErr: "no route",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, tt := range tests {
|
||||||
|
t.Run(tt.name, func(t *testing.T) {
|
||||||
|
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
||||||
|
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
||||||
|
|
||||||
|
if tt.wantErr == "" {
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if err == nil {
|
||||||
|
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
||||||
|
}
|
||||||
|
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||||
|
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
||||||
|
// carries IPv6 addresses.
|
||||||
|
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
||||||
|
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
||||||
|
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
||||||
|
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
||||||
|
}
|
||||||
|
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
||||||
|
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,18 +9,6 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/vishvananda/netlink"
|
"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
|
// testLink returns a minimal netlink.Link whose Attrs().Name is name, so the
|
||||||
@@ -455,185 +443,3 @@ func TestBuildResolvectlArgs(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const (
|
|
||||||
routeTestInboundTag = "tun"
|
|
||||||
routeTestSource = "192.168.100.1"
|
|
||||||
routeTestDNSAddress = "192.168.100.2"
|
|
||||||
)
|
|
||||||
|
|
||||||
// port53Rule sends DNS queries arriving from the interface to the dns outbound.
|
|
||||||
func port53Rule() *router.RoutingRule {
|
|
||||||
return &router.RoutingRule{
|
|
||||||
InboundTag: []string{routeTestInboundTag},
|
|
||||||
PortList: &net.PortList{Range: []*net.PortRange{net.SinglePortRange(53)}},
|
|
||||||
TargetTag: &router.RoutingRule_Tag{Tag: "dns"},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// sourceBlockRule diverts traffic from one address, which is the shape of a rule
|
|
||||||
// that only matches because the real request carries a source.
|
|
||||||
func sourceBlockRule(ip []byte) *router.RoutingRule {
|
|
||||||
return &router.RoutingRule{
|
|
||||||
SourceIp: []*geodata.IPRule{{
|
|
||||||
Value: &geodata.IPRule_Custom{
|
|
||||||
Custom: &geodata.CIDRRule{
|
|
||||||
Cidr: &geodata.CIDR{Ip: ip, Prefix: 32},
|
|
||||||
},
|
|
||||||
},
|
|
||||||
}},
|
|
||||||
TargetTag: &router.RoutingRule_Tag{Tag: "block"},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// newRouteTestContext builds a real but unstarted instance: no TUN device, no
|
|
||||||
// running resolver. The instance is placed in the context through the key core
|
|
||||||
// exports for tests.
|
|
||||||
func newRouteTestContext(t *testing.T, withDNSApp bool, nameServers []*appdns.NameServer, rules []*router.RoutingRule) context.Context {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
apps := []*serial.TypedMessage{
|
|
||||||
serial.ToTypedMessage(&dispatcher.Config{}),
|
|
||||||
serial.ToTypedMessage(&proxyman.InboundConfig{}),
|
|
||||||
serial.ToTypedMessage(&proxyman.OutboundConfig{}),
|
|
||||||
serial.ToTypedMessage(&router.Config{Rule: rules}),
|
|
||||||
}
|
|
||||||
if withDNSApp {
|
|
||||||
apps = append(apps, serial.ToTypedMessage(&appdns.Config{NameServer: nameServers}))
|
|
||||||
}
|
|
||||||
|
|
||||||
instance, err := core.New(&core.Config{
|
|
||||||
App: apps,
|
|
||||||
Outbound: []*core.OutboundHandlerConfig{
|
|
||||||
{Tag: "direct", ProxySettings: serial.ToTypedMessage(&freedom.Config{})},
|
|
||||||
{Tag: "dns", ProxySettings: serial.ToTypedMessage(&proxydns.Config{})},
|
|
||||||
{Tag: "block", ProxySettings: serial.ToTypedMessage(&freedom.Config{Firewall: []*freedom.FirewallConfig{{Action: freedom.RuleAction_Block, Delay: &freedom.Range{}}}})},
|
|
||||||
},
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("core.New: %v", err)
|
|
||||||
}
|
|
||||||
t.Cleanup(func() { _ = instance.Close() })
|
|
||||||
|
|
||||||
return context.WithValue(context.Background(), core.XrayKey(1), instance)
|
|
||||||
}
|
|
||||||
|
|
||||||
func udpNameServer(ip []byte) []*appdns.NameServer {
|
|
||||||
return []*appdns.NameServer{{
|
|
||||||
Address: &net.Endpoint{
|
|
||||||
Network: net.Network_UDP,
|
|
||||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Ip{Ip: ip}},
|
|
||||||
Port: 53,
|
|
||||||
},
|
|
||||||
}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// localNameServer is a name server pointed at "localhost", which app/dns
|
|
||||||
// resolves through the system resolver.
|
|
||||||
func localNameServer() *appdns.NameServer {
|
|
||||||
return &appdns.NameServer{
|
|
||||||
Address: &net.Endpoint{
|
|
||||||
Network: net.Network_UDP,
|
|
||||||
Address: &net.IPOrDomain{Address: &net.IPOrDomain_Domain{Domain: "localhost"}},
|
|
||||||
Port: 53,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// These drive the real feature lookup and the real router. verifyDNSRouting is
|
|
||||||
// the same function ConfigureSystemDNS calls, so a false positive here is a
|
|
||||||
// false positive in the takeover decision itself, which is what assertions on
|
|
||||||
// the resolvectl arguments could never catch.
|
|
||||||
func TestVerifyDNSRoutingDecisions(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
name string
|
|
||||||
withDNSApp bool
|
|
||||||
nameServers []*appdns.NameServer
|
|
||||||
rules []*router.RoutingRule
|
|
||||||
wantErr string
|
|
||||||
}{
|
|
||||||
{
|
|
||||||
name: "independent upstream reaches the dns outbound",
|
|
||||||
withDNSApp: true,
|
|
||||||
nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
|
||||||
rules: []*router.RoutingRule{port53Rule()},
|
|
||||||
wantErr: "",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "no dns section falls back to the system resolver",
|
|
||||||
rules: []*router.RoutingRule{port53Rule()},
|
|
||||||
wantErr: "system resolver",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "dns section without name servers falls back too",
|
|
||||||
withDNSApp: true,
|
|
||||||
rules: []*router.RoutingRule{port53Rule()},
|
|
||||||
wantErr: "system resolver",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
// An independent upstream is not enough on its own: name servers are
|
|
||||||
// selected per domain, so a local one can still be the one chosen.
|
|
||||||
// The refusal is deliberately domain-agnostic for that reason.
|
|
||||||
name: "a local name server alongside an independent one",
|
|
||||||
withDNSApp: true,
|
|
||||||
nameServers: append(udpNameServer([]byte{9, 9, 9, 9}), localNameServer()),
|
|
||||||
rules: []*router.RoutingRule{port53Rule()},
|
|
||||||
wantErr: "system resolver",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "a rule on the interface address diverts the real query",
|
|
||||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
|
||||||
rules: []*router.RoutingRule{
|
|
||||||
sourceBlockRule([]byte{192, 168, 100, 1}),
|
|
||||||
port53Rule(),
|
|
||||||
},
|
|
||||||
wantErr: "does not handle DNS",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "a rule on another address does not match it",
|
|
||||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
|
||||||
rules: []*router.RoutingRule{
|
|
||||||
sourceBlockRule([]byte{10, 0, 0, 1}),
|
|
||||||
port53Rule(),
|
|
||||||
},
|
|
||||||
wantErr: "",
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: "no rule matches the query",
|
|
||||||
withDNSApp: true, nameServers: udpNameServer([]byte{9, 9, 9, 9}),
|
|
||||||
wantErr: "no route",
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
for _, tt := range tests {
|
|
||||||
t.Run(tt.name, func(t *testing.T) {
|
|
||||||
ctx := newRouteTestContext(t, tt.withDNSApp, tt.nameServers, tt.rules)
|
|
||||||
err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, routeTestDNSAddress)
|
|
||||||
|
|
||||||
if tt.wantErr == "" {
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
|
||||||
}
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if err == nil {
|
|
||||||
t.Fatalf("expected the takeover to be refused with %q, got nil", tt.wantErr)
|
|
||||||
}
|
|
||||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
|
||||||
t.Errorf("error = %q, want it to contain %q", err.Error(), tt.wantErr)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Without an IPv4 gateway, the takeover uses the first IPv6 one, and the probe
|
|
||||||
// carries IPv6 addresses.
|
|
||||||
func TestVerifyDNSRoutingIPv6(t *testing.T) {
|
|
||||||
ctx := newRouteTestContext(t, true, udpNameServer([]byte{9, 9, 9, 9}), []*router.RoutingRule{port53Rule()})
|
|
||||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, "fc00::1", "fc00::2"); err != nil {
|
|
||||||
t.Fatalf("expected the takeover to be accepted, got: %v", err)
|
|
||||||
}
|
|
||||||
if err := verifyDNSRouting(ctx, routeTestInboundTag, routeTestSource, "fc00::2"); err == nil {
|
|
||||||
t.Fatal("expected mixed IPv4 and IPv6 addresses to be refused")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -710,109 +710,3 @@ func findOutboundInterface(tunIndex int, fixedName string) (*net.Interface, erro
|
|||||||
}
|
}
|
||||||
return net.InterfaceByIndex(int(index))
|
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"
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,120 @@
|
|||||||
|
//go:build windows
|
||||||
|
|
||||||
|
package tun
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"slices"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/errors"
|
||||||
|
"golang.org/x/sys/windows"
|
||||||
|
"golang.zx2c4.com/wireguard/windows/tunnel/winipcfg"
|
||||||
|
)
|
||||||
|
|
||||||
|
// outboundGuard keeps Windows to the binding of autoOutboundsInterface, which
|
||||||
|
// keeps Xray's own connections out of the TUN. With weak host send or
|
||||||
|
// forwarding on for an IP version on the bound interface, Windows sends them
|
||||||
|
// where the routes lead, into the TUN, from that interface's address, and
|
||||||
|
// drops what comes back to that address through the TUN, so they stall.
|
||||||
|
//
|
||||||
|
// For the IP versions routed to the TUN, weak host send is turned off on the
|
||||||
|
// bound interface while the TUN runs, and turned on again when the TUN stops
|
||||||
|
// or another interface takes over. Forwarding is what Mobile Hotspot and
|
||||||
|
// Internet Connection Sharing need, so it is only reported.
|
||||||
|
type outboundGuard struct {
|
||||||
|
sync.Mutex
|
||||||
|
families []winipcfg.AddressFamily
|
||||||
|
luid winipcfg.LUID // of the interface last checked
|
||||||
|
name string // of that interface
|
||||||
|
turnedOff []winipcfg.AddressFamily // where weak host send was turned off on it
|
||||||
|
forwarding bool // whether forwarding was on there
|
||||||
|
stopped bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// check turns weak host send off on the bound interface, and warns when
|
||||||
|
// forwarding comes on there, but not again while it stays on.
|
||||||
|
func (g *outboundGuard) check() {
|
||||||
|
g.Lock()
|
||||||
|
defer g.Unlock()
|
||||||
|
if g.stopped {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var luid winipcfg.LUID
|
||||||
|
var name string
|
||||||
|
if iface := updater.Get(); iface != nil {
|
||||||
|
luid, _ = winipcfg.LUIDFromIndex(uint32(iface.Index))
|
||||||
|
name = iface.Name
|
||||||
|
}
|
||||||
|
if luid != g.luid {
|
||||||
|
g.restoreLocked()
|
||||||
|
g.luid, g.name = luid, name
|
||||||
|
g.forwarding = false // to warn about the new interface as well
|
||||||
|
}
|
||||||
|
if luid == 0 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
var forwarding []string
|
||||||
|
for _, family := range g.families {
|
||||||
|
row, err := luid.IPInterface(family)
|
||||||
|
if err != nil {
|
||||||
|
continue // the interface lacks that IP version
|
||||||
|
}
|
||||||
|
if row.ForwardingEnabled {
|
||||||
|
forwarding = append(forwarding, familyName(family))
|
||||||
|
}
|
||||||
|
if !row.WeakHostSend {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := setWeakHostSend(row, false); err != nil {
|
||||||
|
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send off for ", familyName(family), " on ", name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if !slices.Contains(g.turnedOff, family) {
|
||||||
|
g.turnedOff = append(g.turnedOff, family)
|
||||||
|
errors.LogInfo(context.Background(), "[tun] weak host send turned off for ", familyName(family), " on ", name, " while the TUN runs, as Windows would ignore autoOutboundsInterface")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
wasOn := g.forwarding
|
||||||
|
g.forwarding = len(forwarding) > 0
|
||||||
|
if g.forwarding && !wasOn {
|
||||||
|
errors.LogWarning(context.Background(), "[tun] forwarding is on for ", strings.Join(forwarding, " and "), " on ", name, " (Mobile Hotspot and Internet Connection Sharing turn it on), so Windows ignores autoOutboundsInterface there, and Xray's own connections go into the TUN and stall: turn the hotspot off, or have it share the TUN instead of ", name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// restore turns weak host send on again where check turned it off, for good.
|
||||||
|
func (g *outboundGuard) restore() {
|
||||||
|
g.Lock()
|
||||||
|
defer g.Unlock()
|
||||||
|
g.restoreLocked()
|
||||||
|
g.stopped = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *outboundGuard) restoreLocked() {
|
||||||
|
for _, family := range g.turnedOff {
|
||||||
|
row, err := g.luid.IPInterface(family)
|
||||||
|
if err == nil {
|
||||||
|
err = setWeakHostSend(row, true)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
errors.LogWarningInner(context.Background(), err, "[tun] unable to turn weak host send on again for ", familyName(family), " on ", g.name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
g.turnedOff = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func setWeakHostSend(row *winipcfg.MibIPInterfaceRow, on bool) error {
|
||||||
|
row.WeakHostSend = on
|
||||||
|
if row.Family == windows.AF_INET {
|
||||||
|
row.SitePrefixLength = 0 // as SetIpInterfaceEntry requires for IPv4
|
||||||
|
}
|
||||||
|
return row.Set()
|
||||||
|
}
|
||||||
|
|
||||||
|
func familyName(family winipcfg.AddressFamily) string {
|
||||||
|
if family == windows.AF_INET {
|
||||||
|
return "IPv4"
|
||||||
|
}
|
||||||
|
return "IPv6"
|
||||||
|
}
|
||||||
@@ -4,7 +4,6 @@ package tun
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/md5"
|
|
||||||
go_errors "errors"
|
go_errors "errors"
|
||||||
"net"
|
"net"
|
||||||
"net/netip"
|
"net/netip"
|
||||||
@@ -341,46 +340,3 @@ func TestFlushDNSCache(t *testing.T) {
|
|||||||
t.Fatal(err)
|
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,6 +8,20 @@ import (
|
|||||||
"github.com/xtls/xray-core/common/net"
|
"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) {
|
func TestPacketQueueOrderAndClose(t *testing.T) {
|
||||||
q := newPacketQueue(udpQueueLimit)
|
q := newPacketQueue(udpQueueLimit)
|
||||||
for i := 0; i < 3; i++ {
|
for i := 0; i < 3; i++ {
|
||||||
|
|||||||
@@ -0,0 +1,82 @@
|
|||||||
|
package tun
|
||||||
|
|
||||||
|
import (
|
||||||
|
"runtime"
|
||||||
|
"testing"
|
||||||
|
|
||||||
|
"github.com/xtls/xray-core/common/buf"
|
||||||
|
)
|
||||||
|
|
||||||
|
const benchBatch = 64
|
||||||
|
|
||||||
|
// Raw cost of queueing and draining a small burst, as one flow's reader does.
|
||||||
|
func BenchmarkQueueBurstChan(b *testing.B) {
|
||||||
|
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||||
|
p := &buf.Buffer{}
|
||||||
|
b.ReportAllocs()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
for j := 0; j < benchBatch; j++ {
|
||||||
|
ch <- p
|
||||||
|
}
|
||||||
|
for j := 0; j < benchBatch; j++ {
|
||||||
|
<-ch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkQueueBurstPacketQueue(b *testing.B) {
|
||||||
|
q := newPacketQueue(udpQueueLimit)
|
||||||
|
p := &buf.Buffer{}
|
||||||
|
b.ReportAllocs()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
for j := 0; j < benchBatch; j++ {
|
||||||
|
q.push(p)
|
||||||
|
}
|
||||||
|
for j := 0; j < benchBatch; j++ {
|
||||||
|
q.pop()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Producer and consumer on different goroutines; the producer yields when the
|
||||||
|
// queue is full instead of spinning, like a blocking channel send would.
|
||||||
|
func BenchmarkQueueStreamChan(b *testing.B) {
|
||||||
|
ch := make(chan *buf.Buffer, udpQueueLimit)
|
||||||
|
p := &buf.Buffer{}
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
for range ch {
|
||||||
|
}
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
ch <- p
|
||||||
|
}
|
||||||
|
close(ch)
|
||||||
|
<-done
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkQueueStreamPacketQueue(b *testing.B) {
|
||||||
|
q := newPacketQueue(udpQueueLimit)
|
||||||
|
p := &buf.Buffer{}
|
||||||
|
done := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
for {
|
||||||
|
if _, ok := q.pop(); !ok {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
close(done)
|
||||||
|
}()
|
||||||
|
b.ReportAllocs()
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
for !q.push(p) {
|
||||||
|
runtime.Gosched()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
q.close()
|
||||||
|
<-done
|
||||||
|
}
|
||||||
@@ -80,3 +80,43 @@ func TestExpandWfpBlockLeak(t *testing.T) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestLeakCovers(t *testing.T) {
|
||||||
|
for _, c := range []struct {
|
||||||
|
value string
|
||||||
|
protocol string
|
||||||
|
port uint16
|
||||||
|
covers bool
|
||||||
|
}{
|
||||||
|
{"tcp", "tcp", 1, true},
|
||||||
|
{"tcp", "udp", 53, false},
|
||||||
|
{"udp/53", "udp", 53, true},
|
||||||
|
{"udp/53", "udp", 54, false},
|
||||||
|
{"tcp/10-20", "tcp", 10, true},
|
||||||
|
{"tcp/10-20", "tcp", 20, true},
|
||||||
|
{"tcp/10-20", "tcp", 21, false},
|
||||||
|
{"tcp/10-20", "tcp", 9, false},
|
||||||
|
{"53", "udp", 53, true},
|
||||||
|
{"53", "tcp", 53, true},
|
||||||
|
{"10-20", "tcp", 15, true},
|
||||||
|
{"10-20", "udp", 21, false},
|
||||||
|
{"1.1.1.0/24:udp/53", "udp", 53, true},
|
||||||
|
{"[::/0]:tcp", "tcp", 443, true},
|
||||||
|
{"[2001:db8::/32]:53", "tcp", 53, true},
|
||||||
|
{"0.0.0.0/0:icmp", "udp", 53, false},
|
||||||
|
{"all", "udp", 53, true},
|
||||||
|
{"1.1.1.1/32:all", "tcp", 1, true},
|
||||||
|
{"allexceptlan", "udp", 53, false},
|
||||||
|
{"misconfigtun", "udp", 53, false},
|
||||||
|
{"windnsclient", "udp", 53, false},
|
||||||
|
} {
|
||||||
|
l, ok := parseLeak(c.value)
|
||||||
|
if !ok {
|
||||||
|
t.Errorf("%q was not parsed", c.value)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if got := l.covers(c.protocol, c.port); got != c.covers {
|
||||||
|
t.Errorf("%q covers %s/%d = %v", c.value, c.protocol, c.port, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -36,7 +36,6 @@ import (
|
|||||||
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
"github.com/xtls/xray-core/proxy/vless/multiplex"
|
||||||
"github.com/xtls/xray-core/proxy/vless/reverse"
|
"github.com/xtls/xray-core/proxy/vless/reverse"
|
||||||
"github.com/xtls/xray-core/transport"
|
"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/reality"
|
||||||
"github.com/xtls/xray-core/transport/internet/stat"
|
"github.com/xtls/xray-core/transport/internet/stat"
|
||||||
"github.com/xtls/xray-core/transport/internet/tls"
|
"github.com/xtls/xray-core/transport/internet/tls"
|
||||||
@@ -525,12 +524,6 @@ func (h *Handler) Process(ctx context.Context, network net.Network, connection s
|
|||||||
}
|
}
|
||||||
errors.LogInfo(ctx, "received request for ", request.Destination())
|
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)
|
inbound := session.InboundFromContext(ctx)
|
||||||
if inbound == nil {
|
if inbound == nil {
|
||||||
panic("no inbound metadata")
|
panic("no inbound metadata")
|
||||||
|
|||||||
@@ -12,7 +12,6 @@ import (
|
|||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/net"
|
"github.com/xtls/xray-core/common/net"
|
||||||
"github.com/xtls/xray-core/common/session"
|
"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/proxy/vless"
|
||||||
"github.com/xtls/xray-core/transport"
|
"github.com/xtls/xray-core/transport"
|
||||||
)
|
)
|
||||||
@@ -42,19 +41,17 @@ type Client struct {
|
|||||||
|
|
||||||
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
|
func NewClient(ctx context.Context, config *vless.Multiplex, network string, open func(context.Context) (context.Context, *transport.Link, error)) *Client {
|
||||||
c := &Client{config: config}
|
c := &Client{config: config}
|
||||||
maxReuseTimes := uint32(1024)
|
pool := func(concurrency int32) *Pool {
|
||||||
if network == "xdrive" {
|
return NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(concurrency), MaxConnection: 1024}, open)
|
||||||
maxReuseTimes = 0 // unlimited
|
}
|
||||||
config.Concurrency = max(config.Concurrency, 128)
|
if concurrency := config.GetConcurrency(); concurrency > 0 {
|
||||||
if config.XudpConcurrency > 0 {
|
if network == "xdrive" {
|
||||||
config.XudpConcurrency = max(config.XudpConcurrency, 128)
|
concurrency = max(concurrency, 128)
|
||||||
}
|
}
|
||||||
|
c.tcp = pool(concurrency)
|
||||||
}
|
}
|
||||||
if config.Concurrency > 0 {
|
if concurrency := config.GetXudpConcurrency(); concurrency > 0 {
|
||||||
c.tcp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.Concurrency), MaxConnection: maxReuseTimes}, open)
|
c.udp = pool(concurrency)
|
||||||
}
|
|
||||||
if config.XudpConcurrency > 0 {
|
|
||||||
c.udp = NewPool(ctx, ClientStrategy{MaxConcurrency: uint32(config.XudpConcurrency), MaxConnection: maxReuseTimes}, open)
|
|
||||||
}
|
}
|
||||||
return c
|
return c
|
||||||
}
|
}
|
||||||
@@ -75,7 +72,6 @@ func (c *Client) Dispatch(ctx context.Context, link *transport.Link) (bool, erro
|
|||||||
if target.Network == net.Network_UDP && target.Port == 443 {
|
if target.Network == net.Network_UDP && target.Port == 443 {
|
||||||
switch c.config.GetXudpProxyUDP443() {
|
switch c.config.GetXudpProxyUDP443() {
|
||||||
case "reject", "":
|
case "reject", "":
|
||||||
proxy.DropUDP(ctx, link.Reader)
|
|
||||||
return true, errors.New("XUDP rejected UDP/443 traffic")
|
return true, errors.New("XUDP rejected UDP/443 traffic")
|
||||||
case "skip":
|
case "skip":
|
||||||
return false, nil
|
return false, nil
|
||||||
|
|||||||
@@ -26,9 +26,7 @@ func TestClientUDP443Policy(t *testing.T) {
|
|||||||
opened = true
|
opened = true
|
||||||
return nil, nil, context.Canceled
|
return nil, nil, context.Canceled
|
||||||
})
|
})
|
||||||
r, w := pipe.New()
|
handled, err := client.Dispatch(ctx, &transport.Link{})
|
||||||
common.Close(w)
|
|
||||||
handled, err := client.Dispatch(ctx, &transport.Link{Reader: r})
|
|
||||||
wantRejected := policy == "reject"
|
wantRejected := policy == "reject"
|
||||||
if opened || handled != wantRejected || (err != nil) != wantRejected {
|
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)
|
t.Fatalf("Dispatch() = (%t, %v), opened carrier = %t, want rejected = %t without opening a carrier", handled, err, opened, wantRejected)
|
||||||
|
|||||||
@@ -191,13 +191,6 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
|
|||||||
rec := h.server
|
rec := h.server
|
||||||
var conn stat.Connection
|
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 {
|
if h.testpre > 0 {
|
||||||
h.initpre.Do(func() {
|
h.initpre.Do(func() {
|
||||||
h.preConns = make(chan *ConnExpire)
|
h.preConns = make(chan *ConnExpire)
|
||||||
@@ -279,20 +272,27 @@ func (h *Handler) process(ctx context.Context, link *transport.Link, dialer inte
|
|||||||
request.Address, request.Port = target.Address, target.Port
|
request.Address, request.Port = target.Address, target.Port
|
||||||
}
|
}
|
||||||
|
|
||||||
|
account := request.User.Account.(*vless.MemoryAccount)
|
||||||
|
|
||||||
requestAddons := &encoding.Addons{
|
requestAddons := &encoding.Addons{
|
||||||
Flow: account.Flow,
|
Flow: account.Flow,
|
||||||
}
|
}
|
||||||
|
|
||||||
var input *bytes.Reader
|
var input *bytes.Reader
|
||||||
var rawInput **bytes.Buffer
|
var rawInput **bytes.Buffer
|
||||||
|
allowUDP443 := false
|
||||||
switch requestAddons.Flow {
|
switch requestAddons.Flow {
|
||||||
case vless.XRV + "-udp443":
|
case vless.XRV + "-udp443":
|
||||||
|
allowUDP443 = true
|
||||||
requestAddons.Flow = requestAddons.Flow[:16]
|
requestAddons.Flow = requestAddons.Flow[:16]
|
||||||
fallthrough
|
fallthrough
|
||||||
case vless.XRV:
|
case vless.XRV:
|
||||||
ob.CanSpliceCopy = 2
|
ob.CanSpliceCopy = 2
|
||||||
switch request.Command {
|
switch request.Command {
|
||||||
case protocol.RequestCommandUDP:
|
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:
|
case protocol.RequestCommandTCP, protocol.RequestCommandMux, protocol.RequestCommandRvs:
|
||||||
var target net.Conn
|
var target net.Conn
|
||||||
if commonConn, ok := conn.(*encryption.CommonConn); ok {
|
if commonConn, ok := conn.(*encryption.CommonConn); ok {
|
||||||
|
|||||||
@@ -255,11 +255,10 @@ func DialSystem(ctx context.Context, dest net.Destination, sockopt *SocketConfig
|
|||||||
}
|
}
|
||||||
ips, err := LookupForIP(dest.Address.Domain(), finalStrategy, src)
|
ips, err := LookupForIP(dest.Address.Domain(), finalStrategy, src)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
errors.LogErrorInner(ctx, err, "failed to resolve ip")
|
||||||
if sockopt.DomainStrategy.ForceIP() {
|
if sockopt.DomainStrategy.ForceIP() {
|
||||||
errors.LogErrorInner(ctx, err, "failed to resolve ip for: ", dest.Address.Domain())
|
|
||||||
return nil, err
|
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 {
|
} 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))])
|
dest.Address = net.IPAddress(ips[dice.Roll(len(ips))])
|
||||||
errors.LogInfo(ctx, "replace destination with "+dest.String())
|
errors.LogInfo(ctx, "replace destination with "+dest.String())
|
||||||
|
|||||||
@@ -175,14 +175,7 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
|||||||
c.decref(msg, addr)
|
c.decref(msg, addr)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
kind := decoded[8] & 0x3F
|
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) {
|
||||||
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.Response = true
|
||||||
msg.Header.Authoritative = true
|
msg.Header.Authoritative = true
|
||||||
msg.Header.RCode = dnsmessage.RCodeSuccess
|
msg.Header.RCode = dnsmessage.RCodeSuccess
|
||||||
@@ -208,14 +201,14 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
|||||||
c.decref(msg, addr)
|
c.decref(msg, addr)
|
||||||
}
|
}
|
||||||
|
|
||||||
if kind == 8 {
|
if decoded[8]&0x3F == 8 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
p := pool4K.Get().([]byte)
|
p := pool4K.Get().([]byte)
|
||||||
p = p[:0]
|
p = p[:0]
|
||||||
if fragmented {
|
if decoded[8]&0xC0 == 0xC0 {
|
||||||
out := pool4K.Get().([]byte)
|
out := pool4K.Get().([]byte)
|
||||||
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[dataOffset:n])
|
n := c.fragManager.Feed(out, FragKey{clientID: clientID, fragID: decoded[12]}, decoded[13], decoded[14], decoded[15:n])
|
||||||
pool4K.Put(p[:cap(p)])
|
pool4K.Put(p[:cap(p)])
|
||||||
if n > 0 {
|
if n > 0 {
|
||||||
p = out[:n]
|
p = out[:n]
|
||||||
@@ -224,7 +217,7 @@ func (c *xdnsServer) read(buf []byte, addr net.Addr) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
p = append(p, decoded[dataOffset:n]...)
|
p = append(p, decoded[12:n]...)
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case <-c.closeCh:
|
case <-c.closeCh:
|
||||||
|
|||||||
@@ -1,77 +0,0 @@
|
|||||||
package xmc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// DefaultDataChannel carries the tunnel byte stream and DefaultPaddingChannel
|
|
||||||
// carries the startup padding. Both ends must agree on the pair, and the
|
|
||||||
// defaults are public constants, so a deployment that wants a different
|
|
||||||
// fingerprint renames them on both sides.
|
|
||||||
DefaultDataChannel = "xmc:data"
|
|
||||||
DefaultPaddingChannel = "xmc:pad"
|
|
||||||
|
|
||||||
// MaxChannelIDLength bounds a channel id. The id travels in every custom
|
|
||||||
// payload header, so a long one is pure overhead; vanilla itself has no
|
|
||||||
// limit beyond the string encoding.
|
|
||||||
MaxChannelIDLength = 128
|
|
||||||
)
|
|
||||||
|
|
||||||
var (
|
|
||||||
channelNamespacePattern = regexp.MustCompile(`^[a-z0-9_.-]+$`)
|
|
||||||
channelPathPattern = regexp.MustCompile(`^[a-z0-9/._-]+$`)
|
|
||||||
)
|
|
||||||
|
|
||||||
// ChannelIDs returns the two configured custom payload channels, filling in the
|
|
||||||
// defaults for empty fields. Both are validated because both ends have to
|
|
||||||
// register them as Minecraft resource locations.
|
|
||||||
func (c *Config) ChannelIDs() (dataChannel, paddingChannel string, err error) {
|
|
||||||
dataChannel = c.DataChannel
|
|
||||||
if dataChannel == "" {
|
|
||||||
dataChannel = DefaultDataChannel
|
|
||||||
}
|
|
||||||
paddingChannel = c.PaddingChannel
|
|
||||||
if paddingChannel == "" {
|
|
||||||
paddingChannel = DefaultPaddingChannel
|
|
||||||
}
|
|
||||||
if err = ValidateChannelID(dataChannel); err != nil {
|
|
||||||
return "", "", fmt.Errorf("data channel: %w", err)
|
|
||||||
}
|
|
||||||
if err = ValidateChannelID(paddingChannel); err != nil {
|
|
||||||
return "", "", fmt.Errorf("padding channel: %w", err)
|
|
||||||
}
|
|
||||||
if dataChannel == paddingChannel {
|
|
||||||
return "", "", fmt.Errorf("data and padding channels must differ: %q", dataChannel)
|
|
||||||
}
|
|
||||||
return dataChannel, paddingChannel, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// ValidateChannelID checks one custom payload id as a Minecraft resource
|
|
||||||
// location: namespace:path with vanilla's character rules. The "minecraft"
|
|
||||||
// namespace is reserved, because every vanilla custom payload id lives there and
|
|
||||||
// reusing one would make the tunnel collide with the game.
|
|
||||||
func ValidateChannelID(id string) error {
|
|
||||||
if id == "" {
|
|
||||||
return fmt.Errorf("empty channel id")
|
|
||||||
}
|
|
||||||
if len(id) > MaxChannelIDLength {
|
|
||||||
return fmt.Errorf("channel id %q is longer than %d bytes", id, MaxChannelIDLength)
|
|
||||||
}
|
|
||||||
namespace, path, found := strings.Cut(id, ":")
|
|
||||||
if !found || strings.Contains(path, ":") {
|
|
||||||
return fmt.Errorf("channel id %q is not namespace:path", id)
|
|
||||||
}
|
|
||||||
if namespace == "" || namespace == ".." || !channelNamespacePattern.MatchString(namespace) {
|
|
||||||
return fmt.Errorf("channel id %q has an invalid namespace: only a-z, 0-9, '_', '.' and '-' are allowed, and it cannot be \"..\"", id)
|
|
||||||
}
|
|
||||||
if namespace == "minecraft" {
|
|
||||||
return fmt.Errorf("channel id %q uses the vanilla \"minecraft\" namespace; vanilla custom payload ids belong to the game", id)
|
|
||||||
}
|
|
||||||
if path == "" || !channelPathPattern.MatchString(path) {
|
|
||||||
return fmt.Errorf("channel id %q has an invalid path: only a-z, 0-9, '_', '-', '.' and '/' are allowed", id)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
@@ -1,188 +0,0 @@
|
|||||||
package xmc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestChannelIDsDefaults(t *testing.T) {
|
|
||||||
dataChannel, paddingChannel, err := (&Config{}).ChannelIDs()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("default channels: %v", err)
|
|
||||||
}
|
|
||||||
if dataChannel != DefaultDataChannel || paddingChannel != DefaultPaddingChannel {
|
|
||||||
t.Fatalf("defaults = %q, %q", dataChannel, paddingChannel)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChannelIDsConfigured(t *testing.T) {
|
|
||||||
config := &Config{DataChannel: "myxmc:stream", PaddingChannel: "myxmc:noise"}
|
|
||||||
dataChannel, paddingChannel, err := config.ChannelIDs()
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("configured channels: %v", err)
|
|
||||||
}
|
|
||||||
if dataChannel != "myxmc:stream" || paddingChannel != "myxmc:noise" {
|
|
||||||
t.Fatalf("channels = %q, %q", dataChannel, paddingChannel)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestChannelIDsRejectEqualChannels(t *testing.T) {
|
|
||||||
config := &Config{DataChannel: "myxmc:same", PaddingChannel: "myxmc:same"}
|
|
||||||
if _, _, err := config.ChannelIDs(); err == nil {
|
|
||||||
t.Fatal("expected an error for one channel used twice")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestValidateChannelID(t *testing.T) {
|
|
||||||
tests := []struct {
|
|
||||||
id string
|
|
||||||
ok bool
|
|
||||||
}{
|
|
||||||
{"xmc:data", true},
|
|
||||||
{"a:b", true},
|
|
||||||
{"my-xmc:v1/main.data", true},
|
|
||||||
{strings.Repeat("a", 126) + ":b", true}, // exactly 128 bytes
|
|
||||||
{"", false},
|
|
||||||
{"xmcdata", false},
|
|
||||||
{"xmc:data:extra", false},
|
|
||||||
{":data", false},
|
|
||||||
{"xmc:", false},
|
|
||||||
{"Xmc:data", false},
|
|
||||||
{"xmc:Data", false},
|
|
||||||
{"..:data", false},
|
|
||||||
{"xmc:data space", false},
|
|
||||||
{"xmc:data!", false},
|
|
||||||
{"minecraft:data", false},
|
|
||||||
{"minecraft:brand", false},
|
|
||||||
{strings.Repeat("a", 127) + ":b", false}, // 129 bytes
|
|
||||||
}
|
|
||||||
for _, test := range tests {
|
|
||||||
err := ValidateChannelID(test.id)
|
|
||||||
if test.ok && err != nil {
|
|
||||||
t.Fatalf("%q: unexpected error %v", test.id, err)
|
|
||||||
}
|
|
||||||
if !test.ok && err == nil {
|
|
||||||
t.Fatalf("%q: expected an error", test.id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestPaddingFramingDependsOnChannelLength pins that the exact frame lengths of
|
|
||||||
// a captured preset follow the configured channel name instead of the default.
|
|
||||||
func TestPaddingFramingDependsOnChannelLength(t *testing.T) {
|
|
||||||
const channel = "my-long-namespace:padding-channel"
|
|
||||||
framing := newPaddingFraming(channel)
|
|
||||||
if got, want := framing.overhead(), defaultPaddingFraming.overhead()+len(channel)-len(DefaultPaddingChannel); got != want {
|
|
||||||
t.Fatalf("overhead = %d, want %d", got, want)
|
|
||||||
}
|
|
||||||
for _, length := range []int{1024, 48 * 1024, 1024 * 1024} {
|
|
||||||
plan, err := framing.plan(length)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("plan %d: %v", length, err)
|
|
||||||
}
|
|
||||||
total := 0
|
|
||||||
for _, frameLength := range plan {
|
|
||||||
if _, ok := framing.frameDataLength(frameLength); !ok {
|
|
||||||
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
|
|
||||||
}
|
|
||||||
total += frameLength
|
|
||||||
}
|
|
||||||
if total != length {
|
|
||||||
t.Fatalf("plan %d totals %d", length, total)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestPaddingChannelIsConfigurable checks that the startup-padding reader drains
|
|
||||||
// exactly the configured channel and leaves every other payload alone.
|
|
||||||
func TestPaddingChannelIsConfigurable(t *testing.T) {
|
|
||||||
const paddingChannel = "myxmc:noise"
|
|
||||||
packetID := paddingFramePacketID(configurationPacketIDs121, false)
|
|
||||||
|
|
||||||
build := func() []byte {
|
|
||||||
var wire bytes.Buffer
|
|
||||||
channel := String(paddingChannel)
|
|
||||||
padding := RestBytes(make([]byte, 64))
|
|
||||||
if err := writePacket(&wire, packetID, &channel, &padding); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
following := String(DefaultDataChannel)
|
|
||||||
payload := RestBytes("tunnel bytes")
|
|
||||||
if err := writePacket(&wire, packetID, &following, &payload); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return wire.Bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
channelOf := func(frame []byte) string {
|
|
||||||
t.Helper()
|
|
||||||
packet, err := readPacket(bytes.NewReader(frame))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
var channel String
|
|
||||||
if err := channel.readFrom(bytes.NewReader(packet.data)); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return string(channel)
|
|
||||||
}
|
|
||||||
|
|
||||||
frame, err := readPastPadding(bytes.NewReader(build()), packetID, paddingChannel)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("readPastPadding: %v", err)
|
|
||||||
}
|
|
||||||
if got := channelOf(frame); got != DefaultDataChannel {
|
|
||||||
t.Fatalf("drained past the configured padding channel, got %q", got)
|
|
||||||
}
|
|
||||||
|
|
||||||
// A different configured name must not silently drop the frame.
|
|
||||||
frame, err = readPastPadding(bytes.NewReader(build()), packetID, "other:pad")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("readPastPadding with another channel: %v", err)
|
|
||||||
}
|
|
||||||
if got := channelOf(frame); got != paddingChannel {
|
|
||||||
t.Fatalf("expected the unrecognized frame back, got %q", got)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestTickStreamUsesConfiguredChannels checks that a configured pair reaches the
|
|
||||||
// wire: data payloads on the data channel, idle ticks on the padding channel.
|
|
||||||
func TestTickStreamUsesConfiguredChannels(t *testing.T) {
|
|
||||||
const (
|
|
||||||
dataChannel = "myxmc:stream"
|
|
||||||
paddingChannel = "myxmc:noise"
|
|
||||||
)
|
|
||||||
writer := &tickTestWriter{}
|
|
||||||
stream := newTickStream(nil, writer, true, configurationPacketIDs121, dataChannel, paddingChannel)
|
|
||||||
defer stream.Stop()
|
|
||||||
|
|
||||||
if _, err := stream.Write([]byte("hello")); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
time.Sleep(120 * time.Millisecond)
|
|
||||||
stream.Stop()
|
|
||||||
_ = stream.Flush()
|
|
||||||
|
|
||||||
seenData, seenPadding := false, false
|
|
||||||
for _, batch := range writer.snapshot() {
|
|
||||||
for _, packet := range readTickBatch(t, batch) {
|
|
||||||
channel, payload := tickPacketChannelAndPayload(t, packet)
|
|
||||||
switch channel {
|
|
||||||
case dataChannel:
|
|
||||||
seenData = true
|
|
||||||
if !bytes.Equal(payload, []byte("hello")) {
|
|
||||||
t.Fatalf("data payload = %q", payload)
|
|
||||||
}
|
|
||||||
case paddingChannel:
|
|
||||||
seenPadding = true
|
|
||||||
default:
|
|
||||||
t.Fatalf("unexpected channel %q", channel)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !seenData || !seenPadding {
|
|
||||||
t.Fatalf("configured channels not used: data=%v padding=%v", seenData, seenPadding)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -23,11 +23,6 @@ type clientConn struct {
|
|||||||
|
|
||||||
state clientState
|
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
|
handshakeLock sync.Mutex
|
||||||
lifecycleMu sync.Mutex
|
lifecycleMu sync.Mutex
|
||||||
closed bool
|
closed bool
|
||||||
@@ -35,11 +30,9 @@ type clientConn struct {
|
|||||||
password string
|
password string
|
||||||
rsaPublicKey []byte
|
rsaPublicKey []byte
|
||||||
hostname string
|
hostname string
|
||||||
dataChannel string
|
|
||||||
paddingChannel string
|
|
||||||
yggdrasil *yggdrasilAuth
|
yggdrasil *yggdrasilAuth
|
||||||
paddingSchedule []paddingTurn
|
paddingSchedule []paddingTurn
|
||||||
packet *tickStream
|
packet *packetStream
|
||||||
deadlines *connectionDeadlines
|
deadlines *connectionDeadlines
|
||||||
|
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
@@ -53,7 +46,7 @@ var (
|
|||||||
clientStateProxy clientState = 2
|
clientStateProxy clientState = 2
|
||||||
)
|
)
|
||||||
|
|
||||||
func newClientConn(c net.Conn, protocol protocolVersion, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth, dataChannel, paddingChannel string) (*clientConn, error) {
|
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth) (*clientConn, error) {
|
||||||
if len(rsaPublicKey) == 0 && yggdrasil == nil {
|
if len(rsaPublicKey) == 0 && yggdrasil == nil {
|
||||||
return nil, fmt.Errorf("empty rsa public key")
|
return nil, fmt.Errorf("empty rsa public key")
|
||||||
}
|
}
|
||||||
@@ -68,14 +61,11 @@ func newClientConn(c net.Conn, protocol protocolVersion, profiles []loginProfile
|
|||||||
writer: c,
|
writer: c,
|
||||||
c: c,
|
c: c,
|
||||||
state: clientStateHandshake,
|
state: clientStateHandshake,
|
||||||
protocol: protocol,
|
|
||||||
handshakeLock: sync.Mutex{},
|
handshakeLock: sync.Mutex{},
|
||||||
profiles: profiles,
|
profiles: profiles,
|
||||||
password: password,
|
password: password,
|
||||||
rsaPublicKey: rsaPublicKey,
|
rsaPublicKey: rsaPublicKey,
|
||||||
hostname: hostname,
|
hostname: hostname,
|
||||||
dataChannel: dataChannel,
|
|
||||||
paddingChannel: paddingChannel,
|
|
||||||
yggdrasil: yggdrasil,
|
yggdrasil: yggdrasil,
|
||||||
paddingSchedule: paddingSchedule,
|
paddingSchedule: paddingSchedule,
|
||||||
deadlines: newConnectionDeadlines(c),
|
deadlines: newConnectionDeadlines(c),
|
||||||
@@ -102,10 +92,10 @@ func (c *clientConn) handshake() error {
|
|||||||
defer func() { _ = c.deadlines.endHandshake() }()
|
defer func() { _ = c.deadlines.endHandshake() }()
|
||||||
|
|
||||||
var (
|
var (
|
||||||
protocolNumber Varint = c.protocol.number
|
protocolVersion Varint = Varint(775)
|
||||||
serverAddress String = String(c.hostname)
|
serverAddress String = String(c.hostname)
|
||||||
serverPort UnsignedShort = UnsignedShort(25565)
|
serverPort UnsignedShort = UnsignedShort(25565)
|
||||||
nextState Varint = Varint(2)
|
nextState Varint = Varint(2)
|
||||||
)
|
)
|
||||||
|
|
||||||
host, portString, err := net.SplitHostPort(c.c.RemoteAddr().String())
|
host, portString, err := net.SplitHostPort(c.c.RemoteAddr().String())
|
||||||
@@ -120,37 +110,11 @@ func (c *clientConn) handshake() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
err = writePacket(c.writer, handshakeServerboundIntention, &protocolNumber, &serverAddress, &serverPort, &nextState)
|
err = writePacket(c.writer, 0x00, &protocolVersion, &serverAddress, &serverPort, &nextState)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("write handshake packet: %w", err)
|
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
|
// Login Start
|
||||||
var selectedProfile loginProfile
|
var selectedProfile loginProfile
|
||||||
if c.yggdrasil != nil {
|
if c.yggdrasil != nil {
|
||||||
@@ -175,156 +139,57 @@ func (c *clientConn) handshake() error {
|
|||||||
}
|
}
|
||||||
username := String(selectedProfile.Username)
|
username := String(selectedProfile.Username)
|
||||||
|
|
||||||
err = writePacket(c.writer, c.protocol.login.serverboundLoginStart, &username, &selectedProfile.UUID)
|
err = writePacket(c.writer, 0x00, &username, &selectedProfile.UUID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("write login start: %w", err)
|
return fmt.Errorf("write login start: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// From here the server drives the login: Encryption Request, then optionally
|
// Encryption Request
|
||||||
// Set Compression, then Login Finished; queries and cookie requests can
|
pkt, err := readPacket(c.reader)
|
||||||
// appear at any point between them, so the client loops over the login
|
if err != nil {
|
||||||
// packets like a vanilla one instead of expecting a fixed sequence.
|
return fmt.Errorf("read encryption request: %w", err)
|
||||||
//
|
}
|
||||||
// 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
|
if pkt.packetID != 0x01 {
|
||||||
// mode), and an offline-mode login skips the encryption request entirely, so
|
return fmt.Errorf("bad encrypt request packet id")
|
||||||
// there is nothing to reproduce and nothing to authenticate.
|
|
||||||
handledEncryption := false
|
|
||||||
joinedSession := false
|
|
||||||
for {
|
|
||||||
pkt, readErr := readPacket(c.reader)
|
|
||||||
if readErr != nil {
|
|
||||||
return fmt.Errorf("read login packet: %w", readErr)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch pkt.packetID {
|
|
||||||
case c.protocol.login.clientboundHello:
|
|
||||||
if handledEncryption {
|
|
||||||
return fmt.Errorf("duplicate encryption request")
|
|
||||||
}
|
|
||||||
handledEncryption = true
|
|
||||||
updatedProfile, joined, helloErr := c.handleEncryptionRequest(pkt, selectedProfile)
|
|
||||||
if helloErr != nil {
|
|
||||||
return helloErr
|
|
||||||
}
|
|
||||||
selectedProfile = updatedProfile
|
|
||||||
joinedSession = joined
|
|
||||||
|
|
||||||
case c.protocol.login.clientboundLoginCompression:
|
|
||||||
// Set Compression is not compressed itself and must be handled before
|
|
||||||
// the packet that follows it, which already uses the compressed
|
|
||||||
// framing. The threshold only decides whether the framing applies:
|
|
||||||
// this writer never compresses, so a server-side threshold does not
|
|
||||||
// shrink padding turns.
|
|
||||||
var threshold Varint
|
|
||||||
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
|
|
||||||
return fmt.Errorf("read login compression threshold: %w", thresholdErr)
|
|
||||||
}
|
|
||||||
if threshold >= 0 {
|
|
||||||
c.reader = newCompressionReader(c.reader)
|
|
||||||
c.writer = newCompressionWriter(c.writer)
|
|
||||||
}
|
|
||||||
|
|
||||||
case c.protocol.login.clientboundCustomQuery:
|
|
||||||
// A vanilla 26.x client answers a login query with a null payload: the
|
|
||||||
// server-driven login extensions of older versions are gone, and a
|
|
||||||
// server that still asks gets an explicit "no answer".
|
|
||||||
if answerErr := c.answerCustomQuery(pkt); answerErr != nil {
|
|
||||||
return answerErr
|
|
||||||
}
|
|
||||||
|
|
||||||
case c.protocol.login.clientboundCookieRequest:
|
|
||||||
if answerErr := c.answerCookieRequest(pkt); answerErr != nil {
|
|
||||||
return answerErr
|
|
||||||
}
|
|
||||||
|
|
||||||
case c.protocol.login.clientboundLoginDisconnect:
|
|
||||||
var reason String
|
|
||||||
if readErr := pkt.readFields(&reason); readErr != nil {
|
|
||||||
return fmt.Errorf("authentication rejected")
|
|
||||||
}
|
|
||||||
if isProtocolVersionReject(string(reason)) {
|
|
||||||
forgetProbedVersions()
|
|
||||||
}
|
|
||||||
return fmt.Errorf("authentication rejected: %s", reason)
|
|
||||||
|
|
||||||
case c.protocol.login.clientboundLoginFinished:
|
|
||||||
if !handledEncryption {
|
|
||||||
return fmt.Errorf("server finished the login without an encryption request: offline-mode servers are not supported")
|
|
||||||
}
|
|
||||||
receivedProfile, finishErr := c.readLoginFinished(pkt)
|
|
||||||
if finishErr != nil {
|
|
||||||
return fmt.Errorf("read login finished fields: %w", finishErr)
|
|
||||||
}
|
|
||||||
// Login Finished is written only after the server's hasJoined
|
|
||||||
// succeeded, so the session is verified and the next login for this
|
|
||||||
// account may join.
|
|
||||||
releaseLogin()
|
|
||||||
if verifyErr := c.verifyLoginProfile(receivedProfile, selectedProfile, joinedSession); verifyErr != nil {
|
|
||||||
return verifyErr
|
|
||||||
}
|
|
||||||
selectedProfile = receivedProfile
|
|
||||||
|
|
||||||
loginAcknowledgedLength, writeErr := writePacketWithLength(c.writer, c.protocol.login.serverboundLoginAcknowledged)
|
|
||||||
if writeErr != nil {
|
|
||||||
return fmt.Errorf("write login acknowledged: %w", writeErr)
|
|
||||||
}
|
|
||||||
return c.startProxy(loginAcknowledgedLength)
|
|
||||||
|
|
||||||
default:
|
|
||||||
return fmt.Errorf("unexpected login packet: 0x%02x", pkt.packetID)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
// 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 (
|
var (
|
||||||
serverId String
|
serverId String
|
||||||
publicKey Bytes
|
publicKey Bytes
|
||||||
verifyToken Bytes
|
verifyToken Bytes
|
||||||
shouldAuthenticate Boolean
|
|
||||||
)
|
)
|
||||||
|
|
||||||
err := pkt.readFields(&serverId, &publicKey, &verifyToken, &shouldAuthenticate)
|
err = pkt.readFields(&serverId, &publicKey, &verifyToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return profile, false, fmt.Errorf("read encryption request fields: %w", err)
|
return 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) {
|
if c.yggdrasil == nil && !bytes.Equal(publicKey, c.rsaPublicKey) {
|
||||||
return profile, false, fmt.Errorf("server public key mismatch")
|
return fmt.Errorf("server public key mismatch")
|
||||||
}
|
}
|
||||||
|
|
||||||
k, err := x509.ParsePKIXPublicKey(publicKey)
|
k, err := x509.ParsePKIXPublicKey(publicKey)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return profile, false, fmt.Errorf("parse server public key: %w", err)
|
return fmt.Errorf("parse server public key: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
rsaPublicKey, ok := k.(*rsa.PublicKey)
|
rsaPublicKey, ok := k.(*rsa.PublicKey)
|
||||||
if !ok {
|
if !ok {
|
||||||
return profile, false, fmt.Errorf("parse server public key: not rsa")
|
return fmt.Errorf("parse server public key: not rsa")
|
||||||
}
|
}
|
||||||
if rsaPublicKey.N.BitLen() < 1024 {
|
if rsaPublicKey.N.BitLen() < 1024 {
|
||||||
return profile, false, fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen())
|
return fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen())
|
||||||
}
|
}
|
||||||
|
|
||||||
sharedSecret := make([]byte, 16)
|
sharedSecret := make([]byte, 16)
|
||||||
if _, err = rand.Read(sharedSecret); err != nil {
|
if _, err = rand.Read(sharedSecret); err != nil {
|
||||||
return profile, false, fmt.Errorf("generate shared secret: %w", err)
|
return fmt.Errorf("generate shared secret: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
encryptedSharedSecret, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, sharedSecret)
|
encryptedSharedSecret, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, sharedSecret)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return profile, false, fmt.Errorf("encrypt shared secret: %w", err)
|
return fmt.Errorf("encrypt shared secret: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.yggdrasil == nil {
|
if c.yggdrasil == nil {
|
||||||
@@ -333,132 +198,107 @@ func (c *clientConn) handleEncryptionRequest(pkt *mcPacket, profile loginProfile
|
|||||||
|
|
||||||
encryptedVerifyToken, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, verifyToken)
|
encryptedVerifyToken, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, verifyToken)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return profile, false, fmt.Errorf("encrypt verify token: %w", err)
|
return fmt.Errorf("encrypt verify token: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send Encryption Response, then switch the ciphers on: vanilla starts
|
// Send Encryption Response
|
||||||
// encrypting only after the response itself has been written.
|
|
||||||
err = writePacket(
|
err = writePacket(
|
||||||
c.writer,
|
c.writer,
|
||||||
c.protocol.login.serverboundKey,
|
0x01,
|
||||||
(*Bytes)(&encryptedSharedSecret),
|
(*Bytes)(&encryptedSharedSecret),
|
||||||
(*Bytes)(&encryptedVerifyToken),
|
(*Bytes)(&encryptedVerifyToken),
|
||||||
)
|
)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return profile, false, fmt.Errorf("write encryption response: %w", err)
|
return fmt.Errorf("write encryption response: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Enable encryption
|
||||||
c.reader, err = newCryptoReader(c.reader, sharedSecret)
|
c.reader, err = newCryptoReader(c.reader, sharedSecret)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return profile, false, fmt.Errorf("new crypto reader: %w", err)
|
return fmt.Errorf("new crypto reader: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
c.writer, err = newCryptoWriter(c.writer, sharedSecret)
|
c.writer, err = newCryptoWriter(c.writer, sharedSecret)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return profile, false, fmt.Errorf("new crypto writer: %w", err)
|
return fmt.Errorf("new crypto writer: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Online mode: join the session with the digest of the handshake data so the
|
if c.yggdrasil != nil {
|
||||||
// server can verify it through hasJoined. The password mode has no session
|
// Standard online-mode login: join the session with the hash of the
|
||||||
// server; its login is authenticated by the pre-shared password instead.
|
// handshake data, the server verifies it through hasJoined.
|
||||||
if c.yggdrasil == nil {
|
serverID := minecraftServerID(string(serverId), sharedSecret, publicKey)
|
||||||
return profile, false, nil
|
token, joinErr := c.yggdrasil.join(context.Background(), serverID)
|
||||||
|
if joinErr != nil {
|
||||||
|
return fmt.Errorf("yggdrasil session join: %w", joinErr)
|
||||||
|
}
|
||||||
|
profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID)
|
||||||
|
if uuidErr != nil {
|
||||||
|
return fmt.Errorf("yggdrasil session join: %w", uuidErr)
|
||||||
|
}
|
||||||
|
selectedProfile = loginProfile{
|
||||||
|
Username: token.profile.Name,
|
||||||
|
UUID: profileUUID,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
serverID := minecraftServerID(string(serverId), sharedSecret, publicKey)
|
pkt, err = readPacket(c.reader)
|
||||||
token, joinErr := c.yggdrasil.join(context.Background(), serverID)
|
if err != nil {
|
||||||
if joinErr != nil {
|
return fmt.Errorf("read login finished: %w", err)
|
||||||
return profile, false, fmt.Errorf("yggdrasil session join: %w", joinErr)
|
|
||||||
}
|
}
|
||||||
profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID)
|
// Set Compression is not compressed itself and must be handled before the
|
||||||
if uuidErr != nil {
|
// packet that follows it, which already uses the compressed framing. The
|
||||||
return profile, false, fmt.Errorf("yggdrasil session join: %w", uuidErr)
|
// threshold only decides whether the framing applies: this writer never
|
||||||
|
// compresses, so a server-side threshold does not shrink padding turns.
|
||||||
|
if pkt.packetID == 0x03 {
|
||||||
|
var threshold Varint
|
||||||
|
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
|
||||||
|
return fmt.Errorf("read login compression threshold: %w", thresholdErr)
|
||||||
|
}
|
||||||
|
if threshold >= 0 {
|
||||||
|
c.reader = newCompressionReader(c.reader)
|
||||||
|
c.writer = newCompressionWriter(c.writer)
|
||||||
|
}
|
||||||
|
pkt, err = readPacket(c.reader)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("read login finished: %w", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if pkt.packetID == 0x00 {
|
||||||
|
var reason String
|
||||||
|
if readErr := pkt.readFields(&reason); readErr != nil {
|
||||||
|
return fmt.Errorf("authentication rejected")
|
||||||
|
}
|
||||||
|
return fmt.Errorf("authentication rejected: %s", reason)
|
||||||
|
}
|
||||||
|
if pkt.packetID != 0x02 {
|
||||||
|
return fmt.Errorf("bad login finished packet id: %d", pkt.packetID)
|
||||||
}
|
}
|
||||||
return loginProfile{Username: token.profile.Name, UUID: profileUUID}, true, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// answerCustomQuery replies to a login query with a null payload, which is what
|
receivedProfile, err := readLoginSuccess(pkt)
|
||||||
// a vanilla 26.x client sends.
|
if err != nil {
|
||||||
func (c *clientConn) answerCustomQuery(pkt *mcPacket) error {
|
return fmt.Errorf("read login finished fields: %w", err)
|
||||||
var transactionID Varint
|
|
||||||
if err := pkt.readFields(&transactionID); err != nil {
|
|
||||||
return fmt.Errorf("read login query: %w", err)
|
|
||||||
}
|
}
|
||||||
// The answer payload is nullable; a vanilla 26.x client leaves it absent.
|
if c.yggdrasil != nil {
|
||||||
answered := Boolean(false)
|
if !sameProfileIdentity(receivedProfile, selectedProfile) {
|
||||||
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")
|
return fmt.Errorf("login profile mismatch")
|
||||||
}
|
}
|
||||||
if err := c.yggdrasil.verifyLoginProfile(received); err != nil {
|
if verifyErr := c.yggdrasil.verifyLoginProfile(receivedProfile); verifyErr != nil {
|
||||||
return fmt.Errorf("verify login profile: %w", err)
|
return fmt.Errorf("verify login profile: %w", verifyErr)
|
||||||
}
|
|
||||||
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")
|
||||||
}
|
}
|
||||||
return nil
|
loginAcknowledgedLength, err := writePacketWithLength(c.writer, 0x03)
|
||||||
}
|
if err != nil {
|
||||||
|
return fmt.Errorf("write login acknowledged: %w", err)
|
||||||
// startProxy runs the startup padding and hands the connection to the tick
|
}
|
||||||
// stream. It is called once the login reached the configuration state.
|
c.reader = newPaddingReader(c.reader, true)
|
||||||
func (c *clientConn) startProxy(loginAcknowledgedLength int) error {
|
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil {
|
||||||
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.
|
_ = c.Close() // Unblock the startup reader if writing failed.
|
||||||
return fmt.Errorf("run startup padding: %w", err)
|
return fmt.Errorf("run startup padding: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
packet := newTickStream(c.reader, c.writer, true, c.protocol.configuration, c.dataChannel, c.paddingChannel)
|
packet := newPacketStream(c.reader, c.writer, true)
|
||||||
c.lifecycleMu.Lock()
|
c.lifecycleMu.Lock()
|
||||||
if c.closed {
|
if c.closed {
|
||||||
c.lifecycleMu.Unlock()
|
c.lifecycleMu.Unlock()
|
||||||
@@ -499,10 +339,6 @@ func (c *clientConn) Close() error {
|
|||||||
c.lifecycleMu.Unlock()
|
c.lifecycleMu.Unlock()
|
||||||
c.closeOnce.Do(func() { close(c.done) })
|
c.closeOnce.Do(func() { close(c.done) })
|
||||||
if packet != nil {
|
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()
|
packet.Stop()
|
||||||
}
|
}
|
||||||
return c.c.Close()
|
return c.c.Close()
|
||||||
|
|||||||
@@ -1,12 +1,10 @@
|
|||||||
package xmc
|
package xmc
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"math"
|
"math"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/xtls/xray-core/common/errors"
|
|
||||||
"github.com/xtls/xray-core/common/net"
|
"github.com/xtls/xray-core/common/net"
|
||||||
"github.com/xtls/xray-core/transport/internet/finalmask"
|
"github.com/xtls/xray-core/transport/internet/finalmask"
|
||||||
)
|
)
|
||||||
@@ -32,49 +30,6 @@ func (c *Config) wrapClientAuth() (*yggdrasilAuth, error) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// gameVersion resolves an explicitly configured protocol row. A configured
|
|
||||||
// value has to be a known row, because a guessed packet id breaks the login in a
|
|
||||||
// way that looks like a network failure.
|
|
||||||
func (c *Config) gameVersion() (protocolVersion, error) {
|
|
||||||
if err := ValidateProtocolVersion(c.ProtocolVersion); err != nil {
|
|
||||||
return protocolVersion{}, err
|
|
||||||
}
|
|
||||||
if c.ProtocolVersion == 0 {
|
|
||||||
return latestProtocolVersion, nil
|
|
||||||
}
|
|
||||||
version, _ := protocolVersionByNumber(Varint(c.ProtocolVersion))
|
|
||||||
return version, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// clientProtocol resolves the row the client advertises in its handshake. A
|
|
||||||
// configured protocol_version is used as-is; zero asks the peer for its status,
|
|
||||||
// because a vanilla server rejects a client that names another version, and the
|
|
||||||
// status response carries the version its login expects.
|
|
||||||
//
|
|
||||||
// The probe is cached per destination, so a normal connection pays it once in a
|
|
||||||
// while rather than on every dial. A peer that does not answer status (or is
|
|
||||||
// behind another transport) falls back to the newest row, which is what a
|
|
||||||
// client of the newest release sends.
|
|
||||||
func (c *Config) clientProtocol(dest *net.Destination, dialer *finalmask.Dialer) (protocolVersion, error) {
|
|
||||||
if err := ValidateProtocolVersion(c.ProtocolVersion); err != nil {
|
|
||||||
return protocolVersion{}, err
|
|
||||||
}
|
|
||||||
if c.ProtocolVersion != 0 {
|
|
||||||
return c.gameVersion()
|
|
||||||
}
|
|
||||||
|
|
||||||
number, name, err := detectProtocolVersion(dest, c.Hostname, dialer)
|
|
||||||
if err != nil {
|
|
||||||
errors.LogWarning(context.Background(), "XMC: cannot detect the peer's protocol version (", err, "), advertising ", latestProtocolVersion.name, " (", latestProtocolVersion.number, "); set protocolVersion to pin it")
|
|
||||||
return latestProtocolVersion, nil
|
|
||||||
}
|
|
||||||
version, ok := protocolVersionByNumber(number)
|
|
||||||
if !ok {
|
|
||||||
return protocolVersion{}, fmt.Errorf("the peer reports Minecraft %q (protocol %d), which is not in the supported table (%s); set protocolVersion to override the detection", name, number, protocolVersionRange())
|
|
||||||
}
|
|
||||||
return version, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) {
|
func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) {
|
||||||
profiles, err := profilesFromConfig(c.Profiles)
|
profiles, err := profilesFromConfig(c.Profiles)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -84,14 +39,6 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
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()
|
auth, err := c.wrapClientAuth()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -109,7 +56,7 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
|
|||||||
rsaPublicKey = c.RsaPublicKey
|
rsaPublicKey = c.RsaPublicKey
|
||||||
}
|
}
|
||||||
|
|
||||||
cc, err := newClientConn(conn, protocol, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth, dataChannel, paddingChannel)
|
cc, err := newClientConn(conn, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||||
}
|
}
|
||||||
@@ -126,10 +73,6 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
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
|
var verifier *yggdrasilVerifier
|
||||||
if c.Yggdrasil != nil {
|
if c.Yggdrasil != nil {
|
||||||
@@ -142,7 +85,7 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
|
|||||||
return nil, fmt.Errorf("minecraft finalmask: empty profiles")
|
return nil, fmt.Errorf("minecraft finalmask: empty profiles")
|
||||||
}
|
}
|
||||||
|
|
||||||
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier, dataChannel, paddingChannel)
|
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
return nil, fmt.Errorf("minecraft finalmask: %w", err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -189,24 +189,9 @@ type Config struct {
|
|||||||
Yggdrasil *Yggdrasil `protobuf:"bytes,13,opt,name=yggdrasil,proto3" json:"yggdrasil,omitempty"`
|
Yggdrasil *Yggdrasil `protobuf:"bytes,13,opt,name=yggdrasil,proto3" json:"yggdrasil,omitempty"`
|
||||||
// Disables startup padding. The configuration sets this for an explicit
|
// Disables startup padding. The configuration sets this for an explicit
|
||||||
// empty "paddings" array, which an unset repeated field cannot express.
|
// 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"`
|
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
|
unknownFields protoimpl.UnknownFields
|
||||||
// that carries startup padding. Both ends must use the same pair; empty
|
sizeCache protoimpl.SizeCache
|
||||||
// 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() {
|
func (x *Config) Reset() {
|
||||||
@@ -295,27 +280,6 @@ func (x *Config) GetNoPadding() bool {
|
|||||||
return false
|
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 {
|
type Padding struct {
|
||||||
state protoimpl.MessageState `protogen:"open.v1"`
|
state protoimpl.MessageState `protogen:"open.v1"`
|
||||||
LengthMin int64 `protobuf:"varint,1,opt,name=length_min,json=lengthMin,proto3" json:"length_min,omitempty"`
|
LengthMin int64 `protobuf:"varint,1,opt,name=length_min,json=lengthMin,proto3" json:"length_min,omitempty"`
|
||||||
@@ -415,7 +379,7 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
|
|||||||
"\x03api\x18\x01 \x01(\tR\x03api\x12\x1a\n" +
|
"\x03api\x18\x01 \x01(\tR\x03api\x12\x1a\n" +
|
||||||
"\busername\x18\x02 \x01(\tR\busername\x12\x1a\n" +
|
"\busername\x18\x02 \x01(\tR\busername\x12\x1a\n" +
|
||||||
"\bpassword\x18\x03 \x01(\tR\bpassword\x12\x16\n" +
|
"\bpassword\x18\x03 \x01(\tR\bpassword\x12\x16\n" +
|
||||||
"\x06player\x18\x04 \x01(\tR\x06player\"\x92\x04\n" +
|
"\x06player\x18\x04 \x01(\tR\x06player\"\x9b\x03\n" +
|
||||||
"\x06Config\x12\x1a\n" +
|
"\x06Config\x12\x1a\n" +
|
||||||
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
|
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
|
||||||
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
|
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
|
||||||
@@ -426,10 +390,7 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
|
|||||||
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddings\x12N\n" +
|
"\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" +
|
"\tyggdrasil\x18\r \x01(\v20.xray.transport.internet.finalmask.xmc.YggdrasilR\tyggdrasil\x12\x1d\n" +
|
||||||
"\n" +
|
"\n" +
|
||||||
"no_padding\x18\x0e \x01(\bR\tnoPadding\x12!\n" +
|
"no_padding\x18\x0e \x01(\bR\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\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" +
|
"\aPadding\x12\x1d\n" +
|
||||||
"\n" +
|
"\n" +
|
||||||
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
|
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
|
||||||
|
|||||||
@@ -53,21 +53,6 @@ message Config {
|
|||||||
// Disables startup padding. The configuration sets this for an explicit
|
// Disables startup padding. The configuration sets this for an explicit
|
||||||
// empty "paddings" array, which an unset repeated field cannot express.
|
// empty "paddings" array, which an unset repeated field cannot express.
|
||||||
bool no_padding = 14;
|
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 {
|
message Padding {
|
||||||
|
|||||||
@@ -16,10 +16,10 @@ func TestClientRejectsLongLegacyPassword(t *testing.T) {
|
|||||||
profiles := []loginProfile{{Username: "TestUser"}}
|
profiles := []loginProfile{{Username: "TestUser"}}
|
||||||
publicKey := []byte{0x01}
|
publicKey := []byte{0x01}
|
||||||
|
|
||||||
if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); err != nil {
|
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil); err != nil {
|
||||||
t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err)
|
t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err)
|
||||||
}
|
}
|
||||||
if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); err == nil {
|
if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil); err == nil {
|
||||||
t.Fatal("expected the long password to be rejected")
|
t.Fatal("expected the long password to be rejected")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -130,7 +130,7 @@ func TestCloseCancelsPaddingPause(t *testing.T) {
|
|||||||
client, server := net.Pipe()
|
client, server := net.Pipe()
|
||||||
defer server.Close()
|
defer server.Close()
|
||||||
|
|
||||||
conn, err := newClientConn(client, latestProtocolVersion, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel)
|
conn, err := newClientConn(client, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
package xmc
|
package xmc
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
|
||||||
"crypto/rsa"
|
"crypto/rsa"
|
||||||
"crypto/sha256"
|
"crypto/sha256"
|
||||||
"fmt"
|
"fmt"
|
||||||
@@ -14,16 +13,9 @@ type sha256Stream struct {
|
|||||||
buf []byte
|
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 {
|
func newSHA256Stream(seed []byte) *sha256Stream {
|
||||||
return &sha256Stream{
|
return &sha256Stream{
|
||||||
seed: bytes.Clone(seed),
|
seed: seed,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,8 +56,6 @@ func derivePrime(stream *sha256Stream) *big.Int {
|
|||||||
func DeriveRSAKey(password string) (*rsa.PrivateKey, error) {
|
func DeriveRSAKey(password string) (*rsa.PrivateKey, error) {
|
||||||
seed := []byte(password)
|
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")...))
|
pStream := newSHA256Stream(append(seed, []byte("-p-prime")...))
|
||||||
qStream := newSHA256Stream(append(seed, []byte("-q-prime")...))
|
qStream := newSHA256Stream(append(seed, []byte("-q-prime")...))
|
||||||
|
|
||||||
|
|||||||
@@ -1,241 +0,0 @@
|
|||||||
package xmc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/sha256"
|
|
||||||
"encoding/hex"
|
|
||||||
"fmt"
|
|
||||||
"math/big"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
)
|
|
||||||
|
|
||||||
// fermatFactorsInOneStep reports whether the public modulus alone discloses the
|
|
||||||
// private key. One iteration of Fermat's method yields a square exactly when N
|
|
||||||
// is the product of two primes with a small gap, which is what happens when p
|
|
||||||
// and q are derived from the same stream (p == q repaired by stepping q to the
|
|
||||||
// next prime).
|
|
||||||
func fermatFactorsInOneStep(n *big.Int) bool {
|
|
||||||
a := new(big.Int).Sqrt(n)
|
|
||||||
a.Add(a, big.NewInt(1))
|
|
||||||
b2 := new(big.Int).Sub(new(big.Int).Mul(a, a), n)
|
|
||||||
if b2.Sign() < 0 {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
b := new(big.Int).Sqrt(b2)
|
|
||||||
return new(big.Int).Mul(b, b).Cmp(b2) == 0
|
|
||||||
}
|
|
||||||
|
|
||||||
func requireUsableKey(t *testing.T, password string) *rsa.PrivateKey {
|
|
||||||
t.Helper()
|
|
||||||
key, err := DeriveRSAKey(password)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("DeriveRSAKey(%q): %v", password, err)
|
|
||||||
}
|
|
||||||
if key.N.BitLen() != 1024 {
|
|
||||||
t.Fatalf("%q: N is %d bits, want 1024", password, key.N.BitLen())
|
|
||||||
}
|
|
||||||
if key.E != 65537 {
|
|
||||||
t.Fatalf("%q: E is %d, want 65537", password, key.E)
|
|
||||||
}
|
|
||||||
if len(key.Primes) != 2 {
|
|
||||||
t.Fatalf("%q: got %d primes, want 2", password, len(key.Primes))
|
|
||||||
}
|
|
||||||
if key.Primes[0].Cmp(key.Primes[1]) == 0 {
|
|
||||||
t.Fatalf("%q (%d bytes): p == q", password, len(password))
|
|
||||||
}
|
|
||||||
if fermatFactorsInOneStep(key.N) {
|
|
||||||
t.Fatalf("%q (%d bytes): N factors at the first Fermat step, p and q are neighbouring primes", password, len(password))
|
|
||||||
}
|
|
||||||
if got := new(big.Int).Mul(key.Primes[0], key.Primes[1]); got.Cmp(key.N) != 0 {
|
|
||||||
t.Fatalf("%q: p*q != N", password)
|
|
||||||
}
|
|
||||||
return key
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestNewSHA256StreamOwnsItsSeed is the direct regression test for the aliasing
|
|
||||||
// defect: the stream hashes its seed on every refill, so it must not retain a
|
|
||||||
// slice whose backing array a caller may still append to.
|
|
||||||
func TestNewSHA256StreamOwnsItsSeed(t *testing.T) {
|
|
||||||
password := []byte(strings.Repeat("k", 100))
|
|
||||||
// Mimic []byte(password) handing out a buffer with spare capacity, which is
|
|
||||||
// what made the two DeriveRSAKey appends overlap in the first place.
|
|
||||||
shared := make([]byte, len(password), len(password)+2*32)
|
|
||||||
copy(shared, password)
|
|
||||||
|
|
||||||
pStream := newSHA256Stream(append(shared, []byte("-p-prime")...))
|
|
||||||
qStream := newSHA256Stream(append(shared, []byte("-q-prime")...))
|
|
||||||
|
|
||||||
if bytes.HasSuffix(pStream.seed, []byte("-q-prime")) {
|
|
||||||
t.Fatalf("p stream seed was rewritten by the q stream's append: %q", pStream.seed)
|
|
||||||
}
|
|
||||||
if !bytes.HasPrefix(pStream.seed, password) || !bytes.HasSuffix(pStream.seed, []byte("-p-prime")) {
|
|
||||||
t.Fatalf("p stream seed = %q, want <password>-p-prime", pStream.seed)
|
|
||||||
}
|
|
||||||
if !bytes.HasPrefix(qStream.seed, password) || !bytes.HasSuffix(qStream.seed, []byte("-q-prime")) {
|
|
||||||
t.Fatalf("q stream seed = %q, want <password>-q-prime", qStream.seed)
|
|
||||||
}
|
|
||||||
if &pStream.seed[0] == &qStream.seed[0] {
|
|
||||||
t.Fatal("both streams share one backing array")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Whatever happens to the caller's buffer afterwards, the streams are fixed.
|
|
||||||
for i := range shared {
|
|
||||||
shared[i] = 'z'
|
|
||||||
}
|
|
||||||
if !bytes.HasPrefix(pStream.seed, password) || !bytes.HasPrefix(qStream.seed, password) {
|
|
||||||
t.Fatal("stream seed follows the caller's buffer after construction")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func referenceStreamBytes(seed string, blocks int) []byte {
|
|
||||||
out := make([]byte, 0, blocks*sha256.Size)
|
|
||||||
for i := 0; i < blocks; i++ {
|
|
||||||
h := sha256.New()
|
|
||||||
h.Write([]byte(seed))
|
|
||||||
fmt.Fprintf(h, "-%d", i)
|
|
||||||
out = append(out, h.Sum(nil)...)
|
|
||||||
}
|
|
||||||
return out
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestSHA256StreamMatchesReference(t *testing.T) {
|
|
||||||
for _, seed := range []string{
|
|
||||||
"",
|
|
||||||
"password",
|
|
||||||
strings.Repeat("a", 113),
|
|
||||||
"00000000-0000-0000-0000-000000000000-p-prime",
|
|
||||||
} {
|
|
||||||
got := make([]byte, 3*sha256.Size)
|
|
||||||
if _, err := newSHA256Stream([]byte(seed)).Read(got); err != nil {
|
|
||||||
t.Fatalf("seed %q: %v", seed, err)
|
|
||||||
}
|
|
||||||
want := referenceStreamBytes(seed, 3)
|
|
||||||
if !bytes.Equal(got, want) {
|
|
||||||
t.Fatalf("seed %q: keystream mismatch", seed)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDeriveRSAKeyAllPasswordLengths sweeps every password length the login
|
|
||||||
// accepts. Lengths whose allocation rounded up left spare capacity for the
|
|
||||||
// "-p-prime"/"-q-prime" appends (33-40, 49-56, 65-72, 81-88, 97-104, 113 at the
|
|
||||||
// time of the fix), but the whole range is checked so a change in allocator size
|
|
||||||
// classes or escape analysis cannot reintroduce the defect unnoticed.
|
|
||||||
func TestDeriveRSAKeyAllPasswordLengths(t *testing.T) {
|
|
||||||
for n := 1; n <= MaxLegacyPasswordLength; n++ {
|
|
||||||
n := n
|
|
||||||
t.Run(fmt.Sprintf("len-%03d", n), func(t *testing.T) {
|
|
||||||
requireUsableKey(t, strings.Repeat("a", n))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDeriveRSAKeyBoundaryLengths pins the lengths next to the capacity
|
|
||||||
// boundaries where the pre-fix code switched between aliasing and reallocating.
|
|
||||||
func TestDeriveRSAKeyBoundaryLengths(t *testing.T) {
|
|
||||||
for _, n := range []int{15, 16, 17, 23, 24, 25, 31, 32, 33, 39, 40, 41, 47, 48, 49, 55, 56, 57, 63, 64, 65, 71, 72, 73, 79, 80, 81, 87, 88, 89, 95, 96, 97, 103, 104, 105, 111, 112, 113} {
|
|
||||||
n := n
|
|
||||||
t.Run(fmt.Sprintf("len-%03d", n), func(t *testing.T) {
|
|
||||||
requireUsableKey(t, strings.Repeat("b", n))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDeriveRSAKeyNonASCIIPasswords covers multi-byte passwords: the affected
|
|
||||||
// ranges are byte lengths, so a 12-character CJK password is a 36-byte one.
|
|
||||||
func TestDeriveRSAKeyNonASCIIPasswords(t *testing.T) {
|
|
||||||
passwords := map[string]string{
|
|
||||||
"cjk-33-bytes": strings.Repeat("密", 11),
|
|
||||||
"cjk-36-bytes": strings.Repeat("密", 12),
|
|
||||||
"emoji-36-bytes": strings.Repeat("🔒", 9),
|
|
||||||
"mixed-utf8": "密码-Password-密码-0123456789-密码-0123",
|
|
||||||
"embedded-nul": "abc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",
|
|
||||||
"all-high-bytes": strings.Repeat("\xff", 40),
|
|
||||||
"surrogate-ish-41": strings.Repeat("é", 20) + "x",
|
|
||||||
}
|
|
||||||
for name, password := range passwords {
|
|
||||||
password := password
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
t.Logf("password is %d bytes", len(password))
|
|
||||||
requireUsableKey(t, password)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDeriveRSAKeyExtremeInputs keeps the derivation total over sizes far
|
|
||||||
// outside what the login accepts: it is called from configuration building, so
|
|
||||||
// it must not panic or depend on a particular capacity.
|
|
||||||
func TestDeriveRSAKeyExtremeInputs(t *testing.T) {
|
|
||||||
cases := map[string]string{
|
|
||||||
"empty": "",
|
|
||||||
"one-byte": "x",
|
|
||||||
"max-accepted": strings.Repeat("m", MaxLegacyPasswordLength),
|
|
||||||
"just-over-max": strings.Repeat("m", MaxLegacyPasswordLength+1),
|
|
||||||
"four-kibibytes": strings.Repeat("m", 4096),
|
|
||||||
}
|
|
||||||
for name, password := range cases {
|
|
||||||
password := password
|
|
||||||
t.Run(name, func(t *testing.T) {
|
|
||||||
requireUsableKey(t, password)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDeriveRSAKeyDeterministic checks that both ends of a connection derive the
|
|
||||||
// same key, including when several goroutines build configurations at once.
|
|
||||||
func TestDeriveRSAKeyDeterministic(t *testing.T) {
|
|
||||||
const password = "00000000-0000-0000-0000-000000000000"
|
|
||||||
want := requireUsableKey(t, password).N
|
|
||||||
|
|
||||||
const workers = 8
|
|
||||||
results := make([]*big.Int, workers)
|
|
||||||
var wg sync.WaitGroup
|
|
||||||
for i := 0; i < workers; i++ {
|
|
||||||
wg.Add(1)
|
|
||||||
go func(i int) {
|
|
||||||
defer wg.Done()
|
|
||||||
key, err := DeriveRSAKey(password)
|
|
||||||
if err != nil {
|
|
||||||
panic(err)
|
|
||||||
}
|
|
||||||
results[i] = key.N
|
|
||||||
}(i)
|
|
||||||
}
|
|
||||||
wg.Wait()
|
|
||||||
|
|
||||||
for i, n := range results {
|
|
||||||
if n.Cmp(want) != 0 {
|
|
||||||
t.Fatalf("worker %d derived a different modulus", i)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDeriveRSAKeyKnownAnswers pins the derivation. The key is a wire-level
|
|
||||||
// shared secret: changing it for an unaffected password would break every
|
|
||||||
// existing deployment, so the digests below must only ever change on purpose.
|
|
||||||
// The 8-, 18- and 32-byte entries are byte-identical to what the aliasing code
|
|
||||||
// derived, which is the compatibility promise of the fix; the 36- and 113-byte
|
|
||||||
// entries were the ones whose key had to change.
|
|
||||||
func TestDeriveRSAKeyKnownAnswers(t *testing.T) {
|
|
||||||
cases := []struct {
|
|
||||||
password string
|
|
||||||
nDigest string
|
|
||||||
}{
|
|
||||||
{"password", "cf683eb5c302ca70"},
|
|
||||||
{"padding-regression", "b9e1f7f9b936fb8d"},
|
|
||||||
{strings.Repeat("a", 32), "6692488374c0e7aa"},
|
|
||||||
{"00000000-0000-0000-0000-000000000000", "6d971fd64a5c0981"},
|
|
||||||
{strings.Repeat("m", MaxLegacyPasswordLength), "45b0e2f0dd483585"},
|
|
||||||
}
|
|
||||||
for _, c := range cases {
|
|
||||||
key := requireUsableKey(t, c.password)
|
|
||||||
digest := sha256.Sum256(key.N.Bytes())
|
|
||||||
got := hex.EncodeToString(digest[:8])
|
|
||||||
if got != c.nDigest {
|
|
||||||
t.Fatalf("%d-byte password: N digest %s, want %s (wire-compatibility break)", len(c.password), got, c.nDigest)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,647 +0,0 @@
|
|||||||
package xmc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/x509"
|
|
||||||
"io"
|
|
||||||
"math/big"
|
|
||||||
"net"
|
|
||||||
"strings"
|
|
||||||
"sync"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
// The Encryption Response is the one place where a peer can get an answer out of
|
|
||||||
// the mask before it holds any secret, so every check on it has to be
|
|
||||||
// indistinguishable from every other. These tests drive the real serverConn.login
|
|
||||||
// over a scripted stream, so what the peer writes and what the server answers are
|
|
||||||
// both exact and no socket timing is involved.
|
|
||||||
|
|
||||||
// scriptedServer is one XMC server whose login a test drives packet by packet.
|
|
||||||
type scriptedServer struct {
|
|
||||||
t *testing.T
|
|
||||||
|
|
||||||
key *rsa.PrivateKey
|
|
||||||
conn *serverConn
|
|
||||||
reader *feedReader
|
|
||||||
writer *syncWriter
|
|
||||||
|
|
||||||
challenge []byte
|
|
||||||
|
|
||||||
// requestLength is how many bytes the Encryption Request occupied, so the
|
|
||||||
// answer (everything after it) can be decrypted on its own.
|
|
||||||
requestLength int
|
|
||||||
|
|
||||||
// respond feeds one Encryption Response and returns the server's answer.
|
|
||||||
respond func(sharedSecret, verifyToken []byte) loginOutcome
|
|
||||||
}
|
|
||||||
|
|
||||||
// loginOutcome is what a peer observes after it wrote one Encryption Response:
|
|
||||||
// the bytes the server sent back and the error login() ended with.
|
|
||||||
type loginOutcome struct {
|
|
||||||
answer []byte
|
|
||||||
err error
|
|
||||||
}
|
|
||||||
|
|
||||||
// newScriptedServer runs login() up to the Encryption Response. The peer sends
|
|
||||||
// the Login Start a client would and reads the Encryption Request back.
|
|
||||||
func newScriptedServer(t *testing.T, password string, profiles []loginProfile) *scriptedServer {
|
|
||||||
t.Helper()
|
|
||||||
return newScriptedServerAs(t, password, profiles, profiles[0].Username, profiles[0].UUID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// newScriptedServerAs is newScriptedServer for a peer that logs in as a name the
|
|
||||||
// profile list does not contain, which is how the whitelist rejection is reached.
|
|
||||||
func newScriptedServerAs(t *testing.T, password string, profiles []loginProfile, loginName string, loginUUID UUID) *scriptedServer {
|
|
||||||
t.Helper()
|
|
||||||
|
|
||||||
key, err := DeriveRSAKey("oracle-test-password")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
var inbound bytes.Buffer
|
|
||||||
if err := writePacket(&inbound, latestProtocolVersion.login.serverboundLoginStart, new(String(loginName)), &loginUUID); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
s := &scriptedServer{
|
|
||||||
t: t,
|
|
||||||
key: key,
|
|
||||||
reader: newFeedReader(inbound.Bytes()),
|
|
||||||
writer: &syncWriter{},
|
|
||||||
}
|
|
||||||
s.conn = &serverConn{
|
|
||||||
reader: s.reader,
|
|
||||||
c: &discardConn{},
|
|
||||||
state: serverStateHandshake,
|
|
||||||
protocol: latestProtocolVersion,
|
|
||||||
profiles: profiles,
|
|
||||||
password: password,
|
|
||||||
rsaPrivateKey: key,
|
|
||||||
rsaPublicKey: publicKey,
|
|
||||||
dataChannel: DefaultDataChannel,
|
|
||||||
paddingChannel: DefaultPaddingChannel,
|
|
||||||
deadlines: newConnectionDeadlines(&discardConn{}),
|
|
||||||
done: make(chan struct{}),
|
|
||||||
yggdrasil: nil,
|
|
||||||
paddingSchedule: nil,
|
|
||||||
}
|
|
||||||
// The Encryption Request goes straight to the peer's socket, so it lands in
|
|
||||||
// the same buffer the encrypted answer will.
|
|
||||||
s.conn.writer = s.writer
|
|
||||||
|
|
||||||
loginDone := make(chan error, 1)
|
|
||||||
go func() { loginDone <- s.conn.login() }()
|
|
||||||
|
|
||||||
// The Encryption Request is one packet and the server writes it as it goes;
|
|
||||||
// wait until it is fully there instead of reading a writer that is still
|
|
||||||
// being filled.
|
|
||||||
deadline := time.Now().Add(10 * time.Second)
|
|
||||||
for {
|
|
||||||
// A frame that decoded fully is the only reliable signal that the
|
|
||||||
// server has written all of it; counting frames would accept a
|
|
||||||
// half-written one.
|
|
||||||
if frames, ok := decodeAllPackets(s.writer.snapshot()); ok && frames == 1 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
if time.Now().After(deadline) {
|
|
||||||
select {
|
|
||||||
case loginErr := <-loginDone:
|
|
||||||
t.Fatalf("login returned before the encryption request: %v (wrote % x)", loginErr, s.writer.snapshot())
|
|
||||||
default:
|
|
||||||
}
|
|
||||||
t.Fatalf("the server did not write the encryption request: % x", s.writer.snapshot())
|
|
||||||
}
|
|
||||||
time.Sleep(time.Millisecond)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Parse the Encryption Request from a snapshot: the buffer keeps every byte
|
|
||||||
// the server writes, later answers included.
|
|
||||||
written := s.writer.snapshot()
|
|
||||||
s.requestLength = countFrameBytes(written)
|
|
||||||
request, err := readPacket(bytes.NewReader(written))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("read encryption request: %v", err)
|
|
||||||
}
|
|
||||||
if request.packetID != latestProtocolVersion.login.clientboundHello {
|
|
||||||
t.Fatalf("login packet id = 0x%02x, want the encryption request", request.packetID)
|
|
||||||
}
|
|
||||||
var (
|
|
||||||
serverID String
|
|
||||||
publicKeyField Bytes
|
|
||||||
verifyToken Bytes
|
|
||||||
shouldAuthenticate Boolean
|
|
||||||
)
|
|
||||||
if err := request.readFields(&serverID, &publicKeyField, &verifyToken, &shouldAuthenticate); err != nil {
|
|
||||||
t.Fatalf("read encryption request fields: %v", err)
|
|
||||||
}
|
|
||||||
s.challenge = verifyToken
|
|
||||||
|
|
||||||
// Feed the Encryption Response when the peer answers, and collect the
|
|
||||||
// server's reply afterwards.
|
|
||||||
s.respond = func(sharedSecret, verifyToken []byte) loginOutcome {
|
|
||||||
sharedField := Bytes(append([]byte(nil), sharedSecret...))
|
|
||||||
tokenField := Bytes(append([]byte(nil), verifyToken...))
|
|
||||||
frame, err := encodePacket(latestProtocolVersion.login.serverboundKey, &sharedField, &tokenField)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("encode encryption response: %v", err)
|
|
||||||
}
|
|
||||||
s.reader.feed(frame)
|
|
||||||
return s.await(loginDone)
|
|
||||||
}
|
|
||||||
|
|
||||||
return s
|
|
||||||
}
|
|
||||||
|
|
||||||
// await waits for login() to return and returns everything the server wrote.
|
|
||||||
func (s *scriptedServer) await(done <-chan error) loginOutcome {
|
|
||||||
s.t.Helper()
|
|
||||||
|
|
||||||
select {
|
|
||||||
case err := <-done:
|
|
||||||
return loginOutcome{answer: s.answer(), err: err}
|
|
||||||
case <-time.After(20 * time.Second):
|
|
||||||
s.t.Fatal("login did not return")
|
|
||||||
return loginOutcome{}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// validToken builds the second block a password-mode client sends: the challenge
|
|
||||||
// followed by the password, encrypted with the server's public key.
|
|
||||||
func (s *scriptedServer) validToken(password string) []byte {
|
|
||||||
s.t.Helper()
|
|
||||||
plaintext := append(append([]byte(nil), s.challenge...), []byte(password)...)
|
|
||||||
return s.encrypt(plaintext)
|
|
||||||
}
|
|
||||||
|
|
||||||
// encrypt builds one PKCS#1 v1.5 block with the public key, exactly as a client
|
|
||||||
// does with Cipher.getInstance("RSA"). The ciphertext is emitted in its shortest
|
|
||||||
// form, so the tests also cover a peer whose implementation does not write the
|
|
||||||
// full modulus width.
|
|
||||||
func (s *scriptedServer) encrypt(plaintext []byte) []byte {
|
|
||||||
s.t.Helper()
|
|
||||||
|
|
||||||
k := s.key.Size()
|
|
||||||
if len(plaintext) > k-11 {
|
|
||||||
s.t.Fatalf("plaintext of %d bytes does not fit a %d-byte block", len(plaintext), k)
|
|
||||||
}
|
|
||||||
|
|
||||||
em := make([]byte, k)
|
|
||||||
em[1] = 0x02
|
|
||||||
padding := em[2 : k-1-len(plaintext)]
|
|
||||||
if _, err := io.ReadFull(rand.Reader, padding); err != nil {
|
|
||||||
s.t.Fatal(err)
|
|
||||||
}
|
|
||||||
for i := range padding {
|
|
||||||
for padding[i] == 0 {
|
|
||||||
if _, err := io.ReadFull(rand.Reader, padding[i:i+1]); err != nil {
|
|
||||||
s.t.Fatal(err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
copy(em[k-len(plaintext):], plaintext)
|
|
||||||
|
|
||||||
m := new(big.Int).SetBytes(em)
|
|
||||||
c := new(big.Int).Exp(m, big.NewInt(int64(s.key.E)), s.key.N)
|
|
||||||
return c.Bytes()
|
|
||||||
}
|
|
||||||
|
|
||||||
// answer returns everything the server wrote after the Encryption Request.
|
|
||||||
func (s *scriptedServer) answer() []byte {
|
|
||||||
written := s.writer.snapshot()
|
|
||||||
if s.requestLength > len(written) {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
return append([]byte(nil), written[s.requestLength:]...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// decryptDisconnect decrypts the answer with the session key the test chose and
|
|
||||||
// returns the reason of the Login Disconnect inside it. Every server in these
|
|
||||||
// tests closes with that packet, so a peer that holds the key sees exactly this.
|
|
||||||
func (s *scriptedServer) decryptDisconnect(answer, sessionKey []byte) string {
|
|
||||||
s.t.Helper()
|
|
||||||
|
|
||||||
block, err := newAESCipher(sessionKey)
|
|
||||||
if err != nil {
|
|
||||||
s.t.Fatal(err)
|
|
||||||
}
|
|
||||||
plaintext := make([]byte, len(answer))
|
|
||||||
newCFB8Decrypt(block, sessionKey).XORKeyStream(plaintext, answer)
|
|
||||||
|
|
||||||
packet, err := readPacket(bytes.NewReader(plaintext))
|
|
||||||
if err != nil {
|
|
||||||
s.t.Fatalf("decrypt answer: %v (plaintext % x)", err, plaintext)
|
|
||||||
}
|
|
||||||
if packet.packetID != latestProtocolVersion.login.clientboundLoginDisconnect {
|
|
||||||
s.t.Fatalf("packet id in the encrypted answer = 0x%02x, want a login disconnect", packet.packetID)
|
|
||||||
}
|
|
||||||
var reason String
|
|
||||||
if err := packet.readFields(&reason); err != nil {
|
|
||||||
s.t.Fatalf("read disconnect reason: %v", err)
|
|
||||||
}
|
|
||||||
return string(reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
// decodeAllPackets counts the packets a byte stream holds and reports whether
|
|
||||||
// the stream ended on a packet boundary and every packet decoded. A single
|
|
||||||
// frame that grows while it is being written therefore reports ok == false.
|
|
||||||
func decodeAllPackets(data []byte) (int, bool) {
|
|
||||||
frames := 0
|
|
||||||
rest := data
|
|
||||||
for len(rest) > 0 {
|
|
||||||
var length int
|
|
||||||
size := 0
|
|
||||||
for {
|
|
||||||
if size >= len(rest) {
|
|
||||||
return frames, false
|
|
||||||
}
|
|
||||||
b := rest[size]
|
|
||||||
length |= int(b&0x7f) << (7 * size)
|
|
||||||
size++
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if size+length > len(rest) {
|
|
||||||
return frames, false
|
|
||||||
}
|
|
||||||
if _, err := readPacket(bytes.NewReader(rest[:size+length])); err != nil {
|
|
||||||
return frames, false
|
|
||||||
}
|
|
||||||
rest = rest[size+length:]
|
|
||||||
frames++
|
|
||||||
}
|
|
||||||
return frames, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// syncWriter is the peer's socket: login() writes to it from its own goroutine
|
|
||||||
// while the test reads, so every access is under one lock.
|
|
||||||
type syncWriter struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
buf bytes.Buffer
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *syncWriter) Write(p []byte) (int, error) {
|
|
||||||
w.mu.Lock()
|
|
||||||
defer w.mu.Unlock()
|
|
||||||
return w.buf.Write(p)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (w *syncWriter) snapshot() []byte {
|
|
||||||
w.mu.Lock()
|
|
||||||
defer w.mu.Unlock()
|
|
||||||
return append([]byte(nil), w.buf.Bytes()...)
|
|
||||||
}
|
|
||||||
|
|
||||||
// feedReader hands a running login() the bytes the peer writes, one feed at a
|
|
||||||
// time, which a bytes.Reader cannot do once login() holds it.
|
|
||||||
type feedReader struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
cond *sync.Cond
|
|
||||||
pending []byte
|
|
||||||
closed bool
|
|
||||||
}
|
|
||||||
|
|
||||||
func newFeedReader(initial []byte) *feedReader {
|
|
||||||
r := &feedReader{pending: append([]byte(nil), initial...)}
|
|
||||||
r.cond = sync.NewCond(&r.mu)
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *feedReader) feed(data []byte) {
|
|
||||||
r.mu.Lock()
|
|
||||||
defer r.mu.Unlock()
|
|
||||||
r.pending = append(r.pending, data...)
|
|
||||||
r.cond.Broadcast()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (r *feedReader) Read(p []byte) (int, error) {
|
|
||||||
r.mu.Lock()
|
|
||||||
defer r.mu.Unlock()
|
|
||||||
for len(r.pending) == 0 && !r.closed {
|
|
||||||
r.cond.Wait()
|
|
||||||
}
|
|
||||||
if len(r.pending) == 0 {
|
|
||||||
return 0, io.EOF
|
|
||||||
}
|
|
||||||
n := copy(p, r.pending)
|
|
||||||
r.pending = r.pending[n:]
|
|
||||||
return n, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// discardConn satisfies net.Conn for a scripted server that never blocks.
|
|
||||||
type discardConn struct{}
|
|
||||||
|
|
||||||
func (discardConn) Read([]byte) (int, error) { return 0, io.EOF }
|
|
||||||
func (discardConn) Write(p []byte) (int, error) { return len(p), nil }
|
|
||||||
func (discardConn) Close() error { return nil }
|
|
||||||
func (discardConn) LocalAddr() net.Addr { return nil }
|
|
||||||
func (discardConn) RemoteAddr() net.Addr { return nil }
|
|
||||||
func (discardConn) SetDeadline(time.Time) error { return nil }
|
|
||||||
func (discardConn) SetReadDeadline(time.Time) error { return nil }
|
|
||||||
func (discardConn) SetWriteDeadline(time.Time) error { return nil }
|
|
||||||
|
|
||||||
// TestEncryptionResponseBadSecretIsRandom checks the fallback itself: a block
|
|
||||||
// that does not unpad to exactly sixteen bytes must leave a random secret, not a
|
|
||||||
// truncated one and not the bytes the peer sent.
|
|
||||||
func TestEncryptionResponseBadSecretIsRandom(t *testing.T) {
|
|
||||||
s := newScriptedServer(t, "right-password", []loginProfile{{Username: "TestUser"}})
|
|
||||||
|
|
||||||
bad := s.encrypt(make([]byte, aesKeyLength))
|
|
||||||
bad[0] ^= 0xff
|
|
||||||
|
|
||||||
seen := make(map[string]bool)
|
|
||||||
for range 8 {
|
|
||||||
secret, block, ok := s.conn.decryptSharedSecret(bad)
|
|
||||||
if !ok || block == nil {
|
|
||||||
t.Fatal("a bad block must still yield a session key to carry on with")
|
|
||||||
}
|
|
||||||
seen[string(secret)] = true
|
|
||||||
}
|
|
||||||
if len(seen) < 2 {
|
|
||||||
t.Fatal("every bad block produced the same session key; the fallback is not random")
|
|
||||||
}
|
|
||||||
|
|
||||||
// A block that unpads to the wrong length must take the same fallback. The
|
|
||||||
// plaintext is not a session key, so it must not be used as one.
|
|
||||||
for _, length := range []int{0, 1, 15, 17, 117} {
|
|
||||||
short := s.encrypt(make([]byte, length))
|
|
||||||
first, _, ok := s.conn.decryptSharedSecret(short)
|
|
||||||
if !ok {
|
|
||||||
t.Fatalf("%d-byte message: no session key", length)
|
|
||||||
}
|
|
||||||
second, _, ok := s.conn.decryptSharedSecret(short)
|
|
||||||
if !ok {
|
|
||||||
t.Fatalf("%d-byte message: no session key", length)
|
|
||||||
}
|
|
||||||
if bytes.Equal(first, second) {
|
|
||||||
t.Fatalf("%d-byte message: the fallback secret repeats", length)
|
|
||||||
}
|
|
||||||
if len(first) != aesKeyLength {
|
|
||||||
t.Fatalf("%d-byte message: secret is %d bytes", length, len(first))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
secret, _, ok := s.conn.decryptSharedSecret(s.encrypt(make([]byte, aesKeyLength)))
|
|
||||||
if !ok || !bytes.Equal(secret, make([]byte, aesKeyLength)) {
|
|
||||||
t.Fatalf("a valid block did not yield its plaintext: %x", secret)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestEncryptionResponseDoesNotRevealPadding is the regression test for
|
|
||||||
// GHSA-ggm8-658p-x4mr. The pre-fix server called rsa.DecryptPKCS1v15 and
|
|
||||||
// returned before installing CFB8 when the padding or the plaintext length was
|
|
||||||
// wrong, so an invalid block closed the connection with no answer while a valid
|
|
||||||
// one got an encrypted Login Disconnect: one oracle bit per attempt against a
|
|
||||||
// static, public RSA key. The fixed server carries on with a random secret, so
|
|
||||||
// every one of these blocks must produce an answer of exactly the same length as
|
|
||||||
// the block a peer can verify, and none of them may be rejected before the
|
|
||||||
// cipher is installed.
|
|
||||||
func TestEncryptionResponseDoesNotRevealPadding(t *testing.T) {
|
|
||||||
profiles := []loginProfile{{Username: "TestUser"}}
|
|
||||||
password := "right-password"
|
|
||||||
|
|
||||||
// Baseline: a well-formed block the peer chose the plaintext of, so it can
|
|
||||||
// decrypt the answer. The password is wrong, which is what an oracle query
|
|
||||||
// uses to make the server reach its single rejection.
|
|
||||||
baselineServer := newScriptedServer(t, password, profiles)
|
|
||||||
baseline := baselineServer.respond(baselineServer.encrypt(make([]byte, aesKeyLength)), baselineServer.validToken("wrong-password"))
|
|
||||||
if baseline.err == nil {
|
|
||||||
t.Fatal("the encryption response with a wrong password was accepted")
|
|
||||||
}
|
|
||||||
if len(baseline.answer) == 0 {
|
|
||||||
t.Fatal("a valid block with a wrong password was not answered inside the encrypted stream")
|
|
||||||
}
|
|
||||||
if reason := baselineServer.decryptDisconnect(baseline.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "authservers_down") {
|
|
||||||
t.Fatalf("baseline disconnect reason = %s", reason)
|
|
||||||
}
|
|
||||||
want := len(baseline.answer)
|
|
||||||
|
|
||||||
blocks := []struct {
|
|
||||||
name string
|
|
||||||
make func(*scriptedServer) []byte
|
|
||||||
}{
|
|
||||||
{"valid padding, empty message", func(s *scriptedServer) []byte { return s.encrypt(nil) }},
|
|
||||||
{"valid padding, one-byte message", func(s *scriptedServer) []byte { return s.encrypt([]byte{1}) }},
|
|
||||||
{"valid padding, fifteen-byte message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, 15)) }},
|
|
||||||
{"valid padding, seventeen-byte message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, 17)) }},
|
|
||||||
{"valid padding, longest message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, s.key.Size()-11)) }},
|
|
||||||
{"ciphertext zero", func(s *scriptedServer) []byte { return make([]byte, s.key.Size()) }},
|
|
||||||
{"ciphertext one", func(s *scriptedServer) []byte {
|
|
||||||
block := make([]byte, s.key.Size())
|
|
||||||
block[len(block)-1] = 1
|
|
||||||
return block
|
|
||||||
}},
|
|
||||||
{"ciphertext equal to the modulus", func(s *scriptedServer) []byte {
|
|
||||||
return s.key.N.FillBytes(make([]byte, s.key.Size()))
|
|
||||||
}},
|
|
||||||
{"empty field", func(*scriptedServer) []byte { return nil }},
|
|
||||||
{"field longer than the modulus", func(*scriptedServer) []byte {
|
|
||||||
block := make([]byte, 1023)
|
|
||||||
if _, err := rand.Read(block); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return block
|
|
||||||
}},
|
|
||||||
}
|
|
||||||
|
|
||||||
var fallbackCiphertexts [][]byte
|
|
||||||
for _, tc := range blocks {
|
|
||||||
t.Run(tc.name, func(t *testing.T) {
|
|
||||||
s := newScriptedServer(t, password, profiles)
|
|
||||||
out := s.respond(tc.make(s), s.validToken("wrong-password"))
|
|
||||||
if out.err == nil {
|
|
||||||
t.Fatal("the encryption response was accepted")
|
|
||||||
}
|
|
||||||
if strings.Contains(out.err.Error(), "verify token mismatch") {
|
|
||||||
t.Fatalf("the block was rejected before the cipher was installed: %v", out.err)
|
|
||||||
}
|
|
||||||
if len(out.answer) != want {
|
|
||||||
t.Fatalf("answer is %d bytes, want %d: the response depends on the shared-secret block", len(out.answer), want)
|
|
||||||
}
|
|
||||||
fallbackCiphertexts = append(fallbackCiphertexts, out.answer)
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// The fallback secret is random per connection, so two runs of the same
|
|
||||||
// invalid block must not produce the same answer bytes.
|
|
||||||
t.Run("fallback is fresh per connection", func(t *testing.T) {
|
|
||||||
if len(fallbackCiphertexts) < 2 {
|
|
||||||
t.Fatal("not enough answers collected")
|
|
||||||
}
|
|
||||||
if bytes.Equal(fallbackCiphertexts[0], fallbackCiphertexts[1]) {
|
|
||||||
t.Fatal("the same ciphertext was sent for two random session keys")
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
// The shape of an adaptive query: take a ciphertext that decrypts to a
|
|
||||||
// session key and perturb it one bit at a time. Whatever padding each
|
|
||||||
// perturbation happens to produce, the answer must keep the same length.
|
|
||||||
t.Run("modified captured ciphertexts", func(t *testing.T) {
|
|
||||||
s := newScriptedServer(t, password, profiles)
|
|
||||||
captured := s.encrypt(make([]byte, aesKeyLength))
|
|
||||||
for i := range 16 {
|
|
||||||
modified := append([]byte(nil), captured...)
|
|
||||||
modified[i%len(modified)] ^= 1 << (i % 8)
|
|
||||||
|
|
||||||
query := newScriptedServer(t, password, profiles)
|
|
||||||
out := query.respond(modified, query.validToken("wrong-password"))
|
|
||||||
if out.err == nil {
|
|
||||||
t.Fatal("the modified ciphertext was accepted")
|
|
||||||
}
|
|
||||||
if len(out.answer) != want {
|
|
||||||
t.Fatalf("query %d answered %d bytes, want %d", i, len(out.answer), want)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestEncryptionResponseChallengeIsPubliclyCheckable pins the one difference the
|
|
||||||
// server keeps on purpose: vanilla validates the challenge before it installs
|
|
||||||
// the cipher, so a wrong challenge closes the connection unencrypted. The
|
|
||||||
// challenge is four random bytes the server sent a moment ago, so that shape
|
|
||||||
// discloses nothing.
|
|
||||||
func TestEncryptionResponseChallengeIsPubliclyCheckable(t *testing.T) {
|
|
||||||
profiles := []loginProfile{{Username: "TestUser"}}
|
|
||||||
|
|
||||||
s := newScriptedServer(t, "right-password", profiles)
|
|
||||||
wrongChallenge := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.encrypt([]byte{1, 2, 3, 4}))
|
|
||||||
if wrongChallenge.err == nil || !strings.Contains(wrongChallenge.err.Error(), "verify token mismatch") {
|
|
||||||
t.Fatalf("a wrong challenge was not rejected: %v", wrongChallenge.err)
|
|
||||||
}
|
|
||||||
if len(wrongChallenge.answer) != 0 {
|
|
||||||
t.Fatalf("a bad challenge got %d bytes back, want an unencrypted close", len(wrongChallenge.answer))
|
|
||||||
}
|
|
||||||
|
|
||||||
s = newScriptedServer(t, "right-password", profiles)
|
|
||||||
goodChallenge := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("wrong-password"))
|
|
||||||
if goodChallenge.err == nil {
|
|
||||||
t.Fatal("a wrong password was accepted")
|
|
||||||
}
|
|
||||||
if len(goodChallenge.answer) == 0 {
|
|
||||||
t.Fatal("a good challenge with a wrong password was not answered inside the encrypted stream")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestEncryptionResponseRejectionsAreInsideTheStream checks what a peer that
|
|
||||||
// holds the session key actually receives: a Login Disconnect, with the reason
|
|
||||||
// vanilla uses. The whitelist answer is only reachable after the password
|
|
||||||
// matched, so a guesser never sees it.
|
|
||||||
func TestEncryptionResponseRejectionsAreInsideTheStream(t *testing.T) {
|
|
||||||
t.Run("wrong password", func(t *testing.T) {
|
|
||||||
s := newScriptedServer(t, "right-password", []loginProfile{{Username: "TestUser"}})
|
|
||||||
out := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("wrong-password"))
|
|
||||||
if out.err == nil {
|
|
||||||
t.Fatal("a wrong password was accepted")
|
|
||||||
}
|
|
||||||
if reason := s.decryptDisconnect(out.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "multiplayer.disconnect.authservers_down") {
|
|
||||||
t.Fatalf("disconnect reason = %s", reason)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("unknown profile", func(t *testing.T) {
|
|
||||||
profiles := []loginProfile{{Username: "Known", UUID: UUID{9, 9, 9}}}
|
|
||||||
|
|
||||||
s := newScriptedServerAs(t, "right-password", profiles, "TestUser", UUID{1, 2, 3})
|
|
||||||
out := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("right-password"))
|
|
||||||
if out.err == nil {
|
|
||||||
t.Fatal("an unknown profile was accepted")
|
|
||||||
}
|
|
||||||
if reason := s.decryptDisconnect(out.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "not white-listed") {
|
|
||||||
t.Fatalf("disconnect reason = %s", reason)
|
|
||||||
}
|
|
||||||
|
|
||||||
// The same answer, from a peer that sent a block it cannot use, must be
|
|
||||||
// the same length: the whitelist rejection cannot become an oracle for
|
|
||||||
// the block either.
|
|
||||||
bad := newScriptedServerAs(t, "right-password", profiles, "TestUser", UUID{1, 2, 3})
|
|
||||||
badOut := bad.respond(make([]byte, bad.key.Size()), bad.validToken("right-password"))
|
|
||||||
if badOut.err == nil {
|
|
||||||
t.Fatal("an unknown profile with an invalid shared secret was accepted")
|
|
||||||
}
|
|
||||||
if len(badOut.answer) != len(out.answer) {
|
|
||||||
t.Fatalf("invalid shared secret answered %d bytes, valid one %d", len(badOut.answer), len(out.answer))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestEncryptionResponseExtremeFields checks the shapes at the edges of the two
|
|
||||||
// fields: they must fail cleanly, without a panic and without a different shape
|
|
||||||
// than any other failure, and the field-length limit itself is the only place
|
|
||||||
// where the packet is refused before decryption - which is public framing the
|
|
||||||
// peer chose.
|
|
||||||
func TestEncryptionResponseExtremeFields(t *testing.T) {
|
|
||||||
profiles := []loginProfile{{Username: "TestUser"}}
|
|
||||||
|
|
||||||
baseline := func(t *testing.T, shared, token []byte) loginOutcome {
|
|
||||||
t.Helper()
|
|
||||||
s := newScriptedServer(t, "right-password", profiles)
|
|
||||||
return s.respond(shared, token)
|
|
||||||
}
|
|
||||||
|
|
||||||
t.Run("empty token field", func(t *testing.T) {
|
|
||||||
out := baseline(t, make([]byte, 128), nil)
|
|
||||||
if out.err == nil || !strings.Contains(out.err.Error(), "verify token mismatch") {
|
|
||||||
t.Fatalf("empty token: %v", out.err)
|
|
||||||
}
|
|
||||||
if len(out.answer) != 0 {
|
|
||||||
t.Fatalf("empty token got %d bytes", len(out.answer))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("token field one byte under the packet field limit", func(t *testing.T) {
|
|
||||||
out := baseline(t, make([]byte, 128), make([]byte, 1023))
|
|
||||||
if out.err == nil || !strings.Contains(out.err.Error(), "verify token mismatch") {
|
|
||||||
t.Fatalf("oversized token: %v", out.err)
|
|
||||||
}
|
|
||||||
if len(out.answer) != 0 {
|
|
||||||
t.Fatalf("oversized token got %d bytes", len(out.answer))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("token field at the packet field limit", func(t *testing.T) {
|
|
||||||
out := baseline(t, make([]byte, 128), make([]byte, 1024))
|
|
||||||
if out.err == nil || !strings.Contains(out.err.Error(), "read encrypt response") {
|
|
||||||
t.Fatalf("token field at the limit: %v", out.err)
|
|
||||||
}
|
|
||||||
if len(out.answer) != 0 {
|
|
||||||
t.Fatalf("token field at the limit got %d bytes", len(out.answer))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("shared secret field at the packet field limit", func(t *testing.T) {
|
|
||||||
out := baseline(t, make([]byte, 1024), nil)
|
|
||||||
if out.err == nil || !strings.Contains(out.err.Error(), "read encrypt response") {
|
|
||||||
t.Fatalf("shared secret field at the limit: %v", out.err)
|
|
||||||
}
|
|
||||||
if len(out.answer) != 0 {
|
|
||||||
t.Fatalf("shared secret field at the limit got %d bytes", len(out.answer))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// countFrameBytes returns the byte length of the first frame in data.
|
|
||||||
func countFrameBytes(data []byte) int {
|
|
||||||
var length int
|
|
||||||
size := 0
|
|
||||||
for {
|
|
||||||
if size >= len(data) {
|
|
||||||
return len(data)
|
|
||||||
}
|
|
||||||
b := data[size]
|
|
||||||
length |= int(b&0x7f) << (7 * size)
|
|
||||||
size++
|
|
||||||
if b&0x80 == 0 {
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return size + length
|
|
||||||
}
|
|
||||||
@@ -1,91 +0,0 @@
|
|||||||
package xmc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"crypto/cipher"
|
|
||||||
"crypto/rand"
|
|
||||||
"crypto/rsa"
|
|
||||||
"crypto/subtle"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// aesKeyLength is the shared secret length vanilla's Crypt counts its
|
|
||||||
// cipher on, and the length an XMC client encrypts.
|
|
||||||
aesKeyLength = 16
|
|
||||||
)
|
|
||||||
|
|
||||||
// decryptSharedSecret recovers the AES shared secret and builds its cipher block
|
|
||||||
// without turning the Encryption Response into a Bleichenbacher oracle.
|
|
||||||
//
|
|
||||||
// The wire format is a bare RSA / PKCS#1 v1.5 block, because that is what a
|
|
||||||
// vanilla client writes (Crypt.encryptUsingKey -> Cipher.getInstance("RSA") ->
|
|
||||||
// doFinal) and a mask that answered anything else would stop pairing with one.
|
|
||||||
// Reading it with rsa.DecryptPKCS1v15 and acting on the error - which is what
|
|
||||||
// this server used to do - lets a peer tell a valid block from an invalid one
|
|
||||||
// without knowing the key. The key is static (derived from the password) and
|
|
||||||
// public, so a captured shared secret could then be attacked offline forever.
|
|
||||||
//
|
|
||||||
// rsa.DecryptPKCS1v15SessionKey is the RFC 3218 countermeasure, and the one the
|
|
||||||
// advisory names: a random sixteen-byte secret is chosen first, the block is
|
|
||||||
// decrypted into it, and the random value survives unless the plaintext is
|
|
||||||
// exactly sixteen bytes. The padding verdict and the length verdict are folded
|
|
||||||
// into one constant-time copy, so neither is reported; the private-key operation
|
|
||||||
// runs on the constant-time FIPS module and the padding scan is branch-free.
|
|
||||||
// Nothing downstream can branch on the padding either, because a peer that did
|
|
||||||
// not send a valid block does not learn the secret the server carries on with.
|
|
||||||
//
|
|
||||||
// The challenge block is the opposite case and keeps vanilla's behaviour; see
|
|
||||||
// decryptVerifyToken.
|
|
||||||
func (c *serverConn) decryptSharedSecret(encryptedSharedSecret []byte) ([]byte, cipher.Block, bool) {
|
|
||||||
secret := make([]byte, aesKeyLength)
|
|
||||||
if _, err := rand.Read(secret); err != nil {
|
|
||||||
return nil, nil, false
|
|
||||||
}
|
|
||||||
|
|
||||||
// An error here means the field did not decode to a number below the
|
|
||||||
// modulus: it was longer than the modulus, or equal to or above N. Both are
|
|
||||||
// properties of the peer's own bytes, not a padding verdict, and the random
|
|
||||||
// secret stands either way, so the error is dropped on purpose.
|
|
||||||
_ = rsa.DecryptPKCS1v15SessionKey(nil, c.rsaPrivateKey, encryptedSharedSecret, secret)
|
|
||||||
|
|
||||||
// A secret the AES layer cannot use cannot happen here - the buffer is
|
|
||||||
// sixteen bytes either way - but the caller must not be able to reach a
|
|
||||||
// panic through it, so it folds into the same boolean.
|
|
||||||
block, err := newAESCipher(secret)
|
|
||||||
if err != nil {
|
|
||||||
return nil, nil, false
|
|
||||||
}
|
|
||||||
return secret, block, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// decryptVerifyToken recovers the challenge block. It is not a secret-bearing
|
|
||||||
// plaintext: the challenge is the four random bytes the server sent a moment
|
|
||||||
// ago, so a failed padding here discloses nothing that is not already public.
|
|
||||||
// Vanilla treats it the same way (ServerboundKeyPacket.isChallengeValid turns
|
|
||||||
// bad padding into the same protocol error a wrong challenge produces), and the
|
|
||||||
// outcome is the one difference vanilla draws too: a bad token closes the
|
|
||||||
// connection before the cipher is installed, a good one fails inside it.
|
|
||||||
//
|
|
||||||
// Unlike the shared secret this must return the whole message, because password
|
|
||||||
// mode carries the password after the challenge in the same block, so
|
|
||||||
// rsa.DecryptPKCS1v15 is the right call: its error is the public padding
|
|
||||||
// verdict vanilla already draws, and its length is not secret.
|
|
||||||
func decryptVerifyToken(key *rsa.PrivateKey, encryptedVerifyToken []byte) ([]byte, bool) {
|
|
||||||
plaintext, err := rsa.DecryptPKCS1v15(nil, key, encryptedVerifyToken)
|
|
||||||
if err != nil {
|
|
||||||
return nil, false
|
|
||||||
}
|
|
||||||
return plaintext, true
|
|
||||||
}
|
|
||||||
|
|
||||||
// challengesEqual compares the challenge the server sent with the plaintext the
|
|
||||||
// peer returned. In password mode the password follows the challenge in the same
|
|
||||||
// block, so a longer plaintext that starts with the challenge is a match;
|
|
||||||
// vanilla compares the whole plaintext, which works there because its client
|
|
||||||
// sends the challenge alone. The comparison is constant time, and only the
|
|
||||||
// length check is not, which is public data deciding a public question.
|
|
||||||
func challengesEqual(want, got []byte) bool {
|
|
||||||
if len(got) < len(want) {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
return subtle.ConstantTimeCompare(want, got[:len(want)]) == 1
|
|
||||||
}
|
|
||||||
@@ -9,22 +9,10 @@ import (
|
|||||||
"time"
|
"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) {
|
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) {
|
t.Run("pipe", func(t *testing.T) {
|
||||||
client, server := net.Pipe()
|
client, server := net.Pipe()
|
||||||
testHandshakeWithPadding(t, version, client, server, 64*1024)
|
testHandshakeWithPadding(t, client, server, 64*1024)
|
||||||
})
|
})
|
||||||
t.Run("tcp", func(t *testing.T) {
|
t.Run("tcp", func(t *testing.T) {
|
||||||
listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)})
|
||||||
@@ -50,11 +38,11 @@ func testHandshakeVersions(t *testing.T, version protocolVersion) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
testHandshakeWithPadding(t, version, client, server, maxPaddingTurnLength)
|
testHandshakeWithPadding(t, client, server, maxPaddingTurnLength)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func testHandshakeWithPadding(t *testing.T, version protocolVersion, clientRaw, serverRaw net.Conn, length int64) {
|
func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, length int64) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
defer clientRaw.Close()
|
defer clientRaw.Close()
|
||||||
defer serverRaw.Close()
|
defer serverRaw.Close()
|
||||||
@@ -84,12 +72,12 @@ func testHandshakeWithPadding(t *testing.T, version protocolVersion, clientRaw,
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
client, err := newClientConn(clientRaw, version, profiles, "password", publicKey, "localhost", paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel)
|
client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", paddingSchedule, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
defer client.Close()
|
defer client.Close()
|
||||||
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel)
|
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,308 +0,0 @@
|
|||||||
package xmc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"bytes"
|
|
||||||
"crypto/x509"
|
|
||||||
"io"
|
|
||||||
"net"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
)
|
|
||||||
|
|
||||||
func newLoginTestClient(t *testing.T, conn net.Conn, version protocolVersion) *clientConn {
|
|
||||||
t.Helper()
|
|
||||||
key, err := DeriveRSAKey("login-flow")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
client, err := newClientConn(conn, version, []loginProfile{{Username: "TestUser"}}, "password", publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return client
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestClientHandshakeAdvertisesConfiguredVersion checks that the handshake
|
|
||||||
// carries the row selected in the configuration, which is what lets one binary
|
|
||||||
// pair with servers of different releases.
|
|
||||||
func TestClientHandshakeAdvertisesConfiguredVersion(t *testing.T) {
|
|
||||||
for _, number := range []Varint{767, 775, 777} {
|
|
||||||
version, ok := protocolVersionByNumber(number)
|
|
||||||
if !ok {
|
|
||||||
t.Fatalf("protocol %d is missing from the table", number)
|
|
||||||
}
|
|
||||||
clientRaw, serverRaw := net.Pipe()
|
|
||||||
client := newLoginTestClient(t, clientRaw, version)
|
|
||||||
go func() { _ = client.handshake() }()
|
|
||||||
|
|
||||||
if err := serverRaw.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
packet, err := readPacket(serverRaw)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("protocol %d: read handshake: %v", number, err)
|
|
||||||
}
|
|
||||||
if packet.packetID != handshakeServerboundIntention {
|
|
||||||
t.Fatalf("protocol %d: handshake packet id = 0x%02x", number, packet.packetID)
|
|
||||||
}
|
|
||||||
var (
|
|
||||||
gotNumber Varint
|
|
||||||
address String
|
|
||||||
port UnsignedShort
|
|
||||||
nextState Varint
|
|
||||||
)
|
|
||||||
if err := packet.readFields(&gotNumber, &address, &port, &nextState); err != nil {
|
|
||||||
t.Fatalf("protocol %d: read handshake fields: %v", number, err)
|
|
||||||
}
|
|
||||||
if gotNumber != number {
|
|
||||||
t.Fatalf("handshake advertised %d, want %d", gotNumber, number)
|
|
||||||
}
|
|
||||||
if nextState != 2 {
|
|
||||||
t.Fatalf("handshake intent = %d, want login (2)", nextState)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = clientRaw.Close()
|
|
||||||
_ = serverRaw.Close()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestClientLoginAnswers checks the two optional login exchanges a vanilla 26.x
|
|
||||||
// client answers: a custom query gets a null payload, a cookie request gets an
|
|
||||||
// absent cookie. Both use the ids of the selected version.
|
|
||||||
func TestClientLoginAnswers(t *testing.T) {
|
|
||||||
version := latestProtocolVersion
|
|
||||||
|
|
||||||
t.Run("custom query", func(t *testing.T) {
|
|
||||||
var wire, out bytes.Buffer
|
|
||||||
transactionID := Varint(7)
|
|
||||||
if err := writePacket(&wire, version.login.clientboundCustomQuery, &transactionID, new(String("test:query"))); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
request, err := readPacket(&wire)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
client := &clientConn{protocol: version, writer: &out}
|
|
||||||
if err := client.answerCustomQuery(request); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
answer, err := readPacket(&out)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if answer.packetID != version.login.serverboundCustomQueryAnswer {
|
|
||||||
t.Fatalf("answer packet id = 0x%02x", answer.packetID)
|
|
||||||
}
|
|
||||||
// transaction id 7, then the nullable payload marker for "no payload".
|
|
||||||
if !bytes.Equal(answer.data, []byte{0x07, 0x00}) {
|
|
||||||
t.Fatalf("answer body = %x", answer.data)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("cookie request", func(t *testing.T) {
|
|
||||||
var wire, out bytes.Buffer
|
|
||||||
if err := writePacket(&wire, version.login.clientboundCookieRequest, new(String("test:cookie"))); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
request, err := readPacket(&wire)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
client := &clientConn{protocol: version, writer: &out}
|
|
||||||
if err := client.answerCookieRequest(request); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
answer, err := readPacket(&out)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if answer.packetID != version.login.serverboundCookieResponse {
|
|
||||||
t.Fatalf("answer packet id = 0x%02x", answer.packetID)
|
|
||||||
}
|
|
||||||
var key String
|
|
||||||
if err := answer.readFields(&key); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if string(key) != "test:cookie" {
|
|
||||||
t.Fatalf("cookie key = %q", string(key))
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestReadLoginFinished checks both shapes of the packet: before 26.2 the body
|
|
||||||
// ends after the game profile, from 26.2 on a session id follows it. Trailing
|
|
||||||
// bytes are ignored, because Mojang has appended a field to this packet before.
|
|
||||||
func TestReadLoginFinished(t *testing.T) {
|
|
||||||
for _, version := range []protocolVersion{protocolVersions[0], latestProtocolVersion} {
|
|
||||||
var (
|
|
||||||
wire bytes.Buffer
|
|
||||||
profile = loginProfile{Username: "TestUser", UUID: UUID{1, 2, 3}}
|
|
||||||
name = String("TestUser")
|
|
||||||
)
|
|
||||||
fields := []field{&profile.UUID, &name, &profile.Properties}
|
|
||||||
if version.loginFinishedSessionID {
|
|
||||||
sessionID := UUID{9, 9, 9}
|
|
||||||
fields = append(fields, &sessionID)
|
|
||||||
}
|
|
||||||
if err := writePacket(&wire, version.login.clientboundLoginFinished, fields...); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
packet, err := readPacket(&wire)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
client := &clientConn{protocol: version}
|
|
||||||
got, err := client.readLoginFinished(packet)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("%s (%d): read login finished: %v", version.name, version.number, err)
|
|
||||||
}
|
|
||||||
if got.Username != "TestUser" || got.UUID != profile.UUID {
|
|
||||||
t.Fatalf("%s (%d): profile = %q %x", version.name, version.number, got.Username, got.UUID)
|
|
||||||
}
|
|
||||||
|
|
||||||
// One missing session id must fail, so the flag cannot silently rot.
|
|
||||||
if version.loginFinishedSessionID {
|
|
||||||
var short bytes.Buffer
|
|
||||||
username := String("TestUser")
|
|
||||||
if err := writePacket(&short, version.login.clientboundLoginFinished, &profile.UUID, &username, &profile.Properties); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
packet, err := readPacket(&short)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if _, err := client.readLoginFinished(packet); err == nil {
|
|
||||||
t.Fatalf("%s: login finished without a session id was accepted", version.name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestServerRejectsUnknownProtocolVersion checks the server answers a version
|
|
||||||
// outside the table with the same Login Disconnect a vanilla server sends,
|
|
||||||
// instead of guessing packet ids.
|
|
||||||
func TestServerRejectsUnknownProtocolVersion(t *testing.T) {
|
|
||||||
key, err := DeriveRSAKey("login-flow")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
clientRaw, serverRaw := net.Pipe()
|
|
||||||
defer clientRaw.Close()
|
|
||||||
defer serverRaw.Close()
|
|
||||||
|
|
||||||
server, err := wrapConnServer(serverRaw, []loginProfile{{Username: "TestUser"}}, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, nil, nil, DefaultDataChannel, DefaultPaddingChannel)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
handshakeResult := make(chan error, 1)
|
|
||||||
go func() { handshakeResult <- server.handshake() }()
|
|
||||||
|
|
||||||
if err := clientRaw.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
var (
|
|
||||||
protocolNumber Varint = 999
|
|
||||||
address String = "localhost"
|
|
||||||
port UnsignedShort = 25565
|
|
||||||
nextState Varint = 2
|
|
||||||
)
|
|
||||||
if err := writePacket(clientRaw, handshakeServerboundIntention, &protocolNumber, &address, &port, &nextState); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
packet, err := readPacket(clientRaw)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("read login disconnect: %v", err)
|
|
||||||
}
|
|
||||||
if packet.packetID != latestProtocolVersion.login.clientboundLoginDisconnect {
|
|
||||||
t.Fatalf("disconnect packet id = 0x%02x", packet.packetID)
|
|
||||||
}
|
|
||||||
var reason String
|
|
||||||
if err := packet.readFields(&reason); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if !strings.Contains(string(reason), "multiplayer.disconnect.incompatible") {
|
|
||||||
t.Fatalf("disconnect reason = %s", string(reason))
|
|
||||||
}
|
|
||||||
|
|
||||||
if err := <-handshakeResult; err == nil || !strings.Contains(err.Error(), "unsupported protocol version") {
|
|
||||||
t.Fatalf("handshake error = %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestClientRejectsOfflineLogin checks the client refuses a login that never
|
|
||||||
// asks for encryption: XMC reproduces the online-mode login, and an offline
|
|
||||||
// server has none of it.
|
|
||||||
func TestClientRejectsOfflineLogin(t *testing.T) {
|
|
||||||
version := latestProtocolVersion
|
|
||||||
clientRaw, serverRaw := net.Pipe()
|
|
||||||
defer clientRaw.Close()
|
|
||||||
defer serverRaw.Close()
|
|
||||||
|
|
||||||
client := newLoginTestClient(t, clientRaw, version)
|
|
||||||
handshakeResult := make(chan error, 1)
|
|
||||||
go func() { handshakeResult <- client.handshake() }()
|
|
||||||
|
|
||||||
if err := serverRaw.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if _, err := readPacket(serverRaw); err != nil {
|
|
||||||
t.Fatalf("read handshake: %v", err)
|
|
||||||
}
|
|
||||||
if _, err := readPacket(serverRaw); err != nil {
|
|
||||||
t.Fatalf("read login start: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// An offline-mode server answers Login Start with Login Finished directly.
|
|
||||||
var (
|
|
||||||
profile = loginProfile{Username: "TestUser", UUID: UUID{1}}
|
|
||||||
username = String("TestUser")
|
|
||||||
session = UUID{9}
|
|
||||||
)
|
|
||||||
if err := writePacket(serverRaw, version.login.clientboundLoginFinished, &profile.UUID, &username, &profile.Properties, &session); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
err := <-handshakeResult
|
|
||||||
if err == nil || !strings.Contains(err.Error(), "offline-mode servers are not supported") {
|
|
||||||
t.Fatalf("handshake error = %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestClientRejectsUnauthenticatedServer checks that a server which still
|
|
||||||
// encrypts but tells the client not to authenticate is refused in Yggdrasil
|
|
||||||
// mode: that flag is an offline-mode server.
|
|
||||||
func TestClientRejectsUnauthenticatedServer(t *testing.T) {
|
|
||||||
version := latestProtocolVersion
|
|
||||||
|
|
||||||
var wire bytes.Buffer
|
|
||||||
var (
|
|
||||||
serverID String
|
|
||||||
publicKey Bytes = Bytes{1, 2, 3}
|
|
||||||
challenge Bytes = Bytes{4, 5, 6, 7}
|
|
||||||
shouldAuthenticate Boolean
|
|
||||||
)
|
|
||||||
if err := writePacket(&wire, version.login.clientboundHello, &serverID, &publicKey, &challenge, &shouldAuthenticate); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
request, err := readPacket(&wire)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
client := &clientConn{protocol: version, writer: io.Discard, yggdrasil: &yggdrasilAuth{}}
|
|
||||||
if _, _, err := client.handleEncryptionRequest(request, loginProfile{}); err == nil || !strings.Contains(err.Error(), "offline-mode servers are not supported") {
|
|
||||||
t.Fatalf("handle encryption request error = %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -4,173 +4,52 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
"net"
|
|
||||||
"sync"
|
"sync"
|
||||||
"sync/atomic"
|
"sync/atomic"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
|
configurationClientboundCustomPayload = 0x01
|
||||||
|
configurationServerboundCustomPayload = 0x02
|
||||||
|
configurationKeepAlive = 0x04
|
||||||
|
|
||||||
|
packetChannel = "xmc:data"
|
||||||
maxPacketData = 24 * 1024
|
maxPacketData = 24 * 1024
|
||||||
keepAlivePeriod = 15 * time.Second
|
keepAlivePeriod = 15 * time.Second
|
||||||
|
|
||||||
// tickInterval is one Minecraft game tick. After the handshake the proxy
|
|
||||||
// stream is emitted in one batch per tick so that the connection keeps the
|
|
||||||
// 20 Hz shape of a real client instead of turning into a bulk TCP stream.
|
|
||||||
tickInterval = 50 * time.Millisecond
|
|
||||||
// maxQueuedData bounds proxy data waiting for the next tick. Write blocks
|
|
||||||
// once the queue is full, so a slow peer pushes back to the proxy instead
|
|
||||||
// of growing memory without bound.
|
|
||||||
maxQueuedData = 4 * 1024 * 1024
|
|
||||||
// tickPaddingSize keeps every tick non-empty in both directions, like the
|
|
||||||
// small per-tick packets a real client and server keep sending while idle.
|
|
||||||
tickPaddingSize = 1
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// tickStream carries the raw proxy byte stream in Minecraft configuration
|
// packetStream carries the raw proxy byte stream in Minecraft configuration
|
||||||
// custom payload packets. The configuration state provides bidirectional
|
// custom payload packets. The configuration state provides bidirectional
|
||||||
// payload packets and keep-alives without requiring version-specific world data.
|
// 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
|
reader io.Reader
|
||||||
writer io.Writer
|
writer io.Writer
|
||||||
isClient bool
|
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
|
readMu sync.Mutex
|
||||||
pending []byte
|
|
||||||
|
|
||||||
writeMu sync.Mutex
|
writeMu sync.Mutex
|
||||||
|
pending []byte
|
||||||
queueMu sync.Mutex
|
|
||||||
queueCond *sync.Cond
|
|
||||||
queue []byte
|
|
||||||
closed bool
|
|
||||||
|
|
||||||
keepAliveID atomic.Int64
|
keepAliveID atomic.Int64
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
stopOnce sync.Once
|
stopOnce sync.Once
|
||||||
}
|
}
|
||||||
|
|
||||||
func newTickStream(reader io.Reader, writer io.Writer, isClient bool, packetIDs configurationPacketIDs, dataChannel, paddingChannel string) *tickStream {
|
func newPacketStream(reader io.Reader, writer io.Writer, isClient bool) *packetStream {
|
||||||
s := &tickStream{
|
s := &packetStream{
|
||||||
reader: reader,
|
reader: reader,
|
||||||
writer: writer,
|
writer: writer,
|
||||||
isClient: isClient,
|
isClient: isClient,
|
||||||
packetIDs: packetIDs,
|
done: make(chan struct{}),
|
||||||
dataChannel: dataChannel,
|
|
||||||
paddingChannel: paddingChannel,
|
|
||||||
done: make(chan struct{}),
|
|
||||||
}
|
}
|
||||||
s.queueCond = sync.NewCond(&s.queueMu)
|
|
||||||
go s.tickLoop()
|
|
||||||
if !isClient {
|
if !isClient {
|
||||||
go s.keepAliveLoop()
|
go s.keepAliveLoop()
|
||||||
}
|
}
|
||||||
return s
|
return s
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *tickStream) tickLoop() {
|
func (s *packetStream) Read(p []byte) (int, error) {
|
||||||
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 {
|
if len(p) == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
@@ -191,7 +70,7 @@ func (s *tickStream) Read(p []byte) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if packet.packetID == s.remoteCustomPayloadID() {
|
if packet.packetID == s.remoteCustomPayloadID() {
|
||||||
payload, ok, err := parseCustomPayload(packet, s.dataChannel)
|
payload, ok, err := parseCustomPayload(packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, err
|
return 0, err
|
||||||
}
|
}
|
||||||
@@ -206,99 +85,70 @@ func (s *tickStream) Read(p []byte) (int, error) {
|
|||||||
return n, nil
|
return n, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Everything else in this state is server chatter: the client answers
|
if packet.packetID == configurationKeepAlive {
|
||||||
// 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
|
var id Long
|
||||||
if err := packet.readFields(&id); err != nil {
|
if err := packet.readFields(&id); err != nil {
|
||||||
return 0, fmt.Errorf("read minecraft keep-alive: %w", err)
|
return 0, fmt.Errorf("read minecraft keep-alive: %w", err)
|
||||||
}
|
}
|
||||||
if err := s.writeKeepAlive(s.packetIDs.serverboundKeepAlive, id); err != nil {
|
if s.isClient {
|
||||||
return 0, err
|
if err := s.writeKeepAlive(id); err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
case s.packetIDs.clientboundPing:
|
|
||||||
// Configuration Ping is answered with Pong, like a real client. The
|
|
||||||
// id is a plain 32-bit integer here, not a varint.
|
|
||||||
var id Int
|
|
||||||
if err := packet.readFields(&id); err != nil {
|
|
||||||
return 0, fmt.Errorf("read minecraft ping: %w", err)
|
|
||||||
}
|
|
||||||
if err := s.writePong(id); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
case s.packetIDs.clientboundCookieRequest:
|
|
||||||
if err := s.writeCookieResponse(packet); err != nil {
|
|
||||||
return 0, err
|
|
||||||
}
|
|
||||||
|
|
||||||
case s.packetIDs.clientboundDisconnect:
|
|
||||||
var reason String
|
|
||||||
_ = packet.readFields(&reason)
|
|
||||||
return 0, fmt.Errorf("minecraft disconnected: %s", string(reason))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *tickStream) Write(p []byte) (int, error) {
|
func (s *packetStream) Write(p []byte) (int, error) {
|
||||||
if len(p) == 0 {
|
if len(p) == 0 {
|
||||||
return 0, nil
|
return 0, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
s.queueMu.Lock()
|
s.writeMu.Lock()
|
||||||
for len(s.queue) >= maxQueuedData && !s.closed {
|
defer s.writeMu.Unlock()
|
||||||
s.queueCond.Wait()
|
|
||||||
}
|
|
||||||
if s.closed {
|
|
||||||
s.queueMu.Unlock()
|
|
||||||
return 0, net.ErrClosed
|
|
||||||
}
|
|
||||||
s.queue = append(s.queue, p...)
|
|
||||||
s.queueMu.Unlock()
|
|
||||||
|
|
||||||
return len(p), nil
|
written := 0
|
||||||
|
for written < len(p) {
|
||||||
|
end := written + maxPacketData
|
||||||
|
if end > len(p) {
|
||||||
|
end = len(p)
|
||||||
|
}
|
||||||
|
channel := String(packetChannel)
|
||||||
|
payload := RestBytes(p[written:end])
|
||||||
|
if err := writePacket(s.writer, s.localCustomPayloadID(), &channel, &payload); err != nil {
|
||||||
|
return written, fmt.Errorf("write minecraft custom payload: %w", err)
|
||||||
|
}
|
||||||
|
written = end
|
||||||
|
}
|
||||||
|
|
||||||
|
return written, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *tickStream) Stop() {
|
func (s *packetStream) Stop() {
|
||||||
s.stopOnce.Do(func() {
|
s.stopOnce.Do(func() { close(s.done) })
|
||||||
s.queueMu.Lock()
|
|
||||||
s.closed = true
|
|
||||||
s.queue = nil
|
|
||||||
s.queueCond.Broadcast()
|
|
||||||
s.queueMu.Unlock()
|
|
||||||
close(s.done)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *tickStream) localCustomPayloadID() int {
|
func (s *packetStream) localCustomPayloadID() int {
|
||||||
if s.isClient {
|
if s.isClient {
|
||||||
return s.packetIDs.serverboundCustomPayload
|
return configurationServerboundCustomPayload
|
||||||
}
|
}
|
||||||
return s.packetIDs.clientboundCustomPayload
|
return configurationClientboundCustomPayload
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *tickStream) remoteCustomPayloadID() int {
|
func (s *packetStream) remoteCustomPayloadID() int {
|
||||||
if s.isClient {
|
if s.isClient {
|
||||||
return s.packetIDs.clientboundCustomPayload
|
return configurationClientboundCustomPayload
|
||||||
}
|
}
|
||||||
return s.packetIDs.serverboundCustomPayload
|
return configurationServerboundCustomPayload
|
||||||
}
|
}
|
||||||
|
|
||||||
func parseCustomPayload(packet *mcPacket, dataChannel string) ([]byte, bool, error) {
|
func parseCustomPayload(packet *mcPacket) ([]byte, bool, error) {
|
||||||
r := bytes.NewReader(packet.data)
|
r := bytes.NewReader(packet.data)
|
||||||
var channel String
|
var channel String
|
||||||
if err := channel.readFrom(r); err != nil {
|
if err := channel.readFrom(r); err != nil {
|
||||||
return nil, false, fmt.Errorf("read minecraft custom payload channel: %w", err)
|
return nil, false, fmt.Errorf("read minecraft custom payload channel: %w", err)
|
||||||
}
|
}
|
||||||
if string(channel) != dataChannel {
|
if string(channel) != packetChannel {
|
||||||
return nil, false, nil
|
return nil, false, nil
|
||||||
}
|
}
|
||||||
payload := make([]byte, r.Len())
|
payload := make([]byte, r.Len())
|
||||||
@@ -308,49 +158,23 @@ func parseCustomPayload(packet *mcPacket, dataChannel string) ([]byte, bool, err
|
|||||||
return payload, true, nil
|
return payload, true, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *tickStream) writeKeepAlive(packetID int, id Long) error {
|
func (s *packetStream) writeKeepAlive(id Long) error {
|
||||||
s.writeMu.Lock()
|
s.writeMu.Lock()
|
||||||
defer s.writeMu.Unlock()
|
defer s.writeMu.Unlock()
|
||||||
if err := writePacket(s.writer, packetID, &id); err != nil {
|
if err := writePacket(s.writer, configurationKeepAlive, &id); err != nil {
|
||||||
return fmt.Errorf("write minecraft keep-alive: %w", err)
|
return fmt.Errorf("write minecraft keep-alive: %w", err)
|
||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// writePong answers a configuration Ping, which a vanilla client always does.
|
func (s *packetStream) keepAliveLoop() {
|
||||||
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)
|
ticker := time.NewTicker(keepAlivePeriod)
|
||||||
defer ticker.Stop()
|
defer ticker.Stop()
|
||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ticker.C:
|
case <-ticker.C:
|
||||||
id := Long(s.keepAliveID.Add(1))
|
id := Long(s.keepAliveID.Add(1))
|
||||||
if err := s.writeKeepAlive(s.packetIDs.clientboundKeepAlive, id); err != nil {
|
if err := s.writeKeepAlive(id); err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
case <-s.done:
|
case <-s.done:
|
||||||
|
|||||||
@@ -29,97 +29,19 @@ const (
|
|||||||
// every connection, so it is rejected when the configuration is built.
|
// every connection, so it is rejected when the configuration is built.
|
||||||
maxPaddingScheduleDelay = handshakeTimeout - 10*time.Second
|
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
|
// Serverbound custom payload data is capped at 32767 bytes by
|
||||||
// ServerboundCustomPayloadPacket; keep the same budget in both directions.
|
// ServerboundCustomPayloadPacket; keep the same budget in both directions.
|
||||||
maxPaddingFrameDataLength = 32767
|
maxPaddingFrameDataLength = 32767
|
||||||
|
// Length varint, packet id, channel length varint and the channel itself.
|
||||||
|
paddingFrameOverhead = 1 + 1 + 1 + len(paddingFrameChannel)
|
||||||
)
|
)
|
||||||
|
|
||||||
// defaultPaddingFraming is the framing of the built-in padding channel. A
|
var maxPaddingFrameLength = paddingFrameLength(maxPaddingFrameDataLength)
|
||||||
// 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 {
|
type paddingVariant struct {
|
||||||
chunks []int
|
chunks []int
|
||||||
@@ -175,14 +97,13 @@ func pausePadding(done <-chan struct{}, d time.Duration) error {
|
|||||||
// Minecraft packets that carry nothing to compare an early arrival against, and
|
// 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
|
// the startup reader drains them on its own while this schedule writes. A peer
|
||||||
// that stalls is bounded by maxPaddingScheduleDelay instead.
|
// that stalls is bounded by maxPaddingScheduleDelay instead.
|
||||||
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error, paddingChannel string, packetIDs configurationPacketIDs) error {
|
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error) error {
|
||||||
if len(schedule) == 0 {
|
if len(schedule) == 0 {
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil {
|
if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
framing := newPaddingFraming(paddingChannel)
|
|
||||||
|
|
||||||
for i, turn := range schedule {
|
for i, turn := range schedule {
|
||||||
prefixLength := 0
|
prefixLength := 0
|
||||||
@@ -207,7 +128,7 @@ func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength i
|
|||||||
if err := sleep(delay); err != nil {
|
if err := sleep(delay); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(packetIDs, isClient), framing); err != nil {
|
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil {
|
||||||
return fmt.Errorf("write padding turn %d: %w", i, err)
|
return fmt.Errorf("write padding turn %d: %w", i, err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -274,19 +195,18 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int)
|
|||||||
|
|
||||||
// paddingFramePacketID returns the configuration-state custom payload packet id
|
// paddingFramePacketID returns the configuration-state custom payload packet id
|
||||||
// used by the side that sends the padding bytes; both values come from the
|
// used by the side that sends the padding bytes; both values come from the
|
||||||
// negotiated version's configuration protocol, so no proxy-specific id ever
|
// vanilla configuration protocol, so no proxy-specific id ever reaches the wire.
|
||||||
// reaches the wire.
|
func paddingFramePacketID(isClient bool) int {
|
||||||
func paddingFramePacketID(packetIDs configurationPacketIDs, isClient bool) int {
|
|
||||||
if isClient {
|
if isClient {
|
||||||
return packetIDs.serverboundCustomPayload
|
return configurationServerboundCustomPayload
|
||||||
}
|
}
|
||||||
return packetIDs.clientboundCustomPayload
|
return configurationClientboundCustomPayload
|
||||||
}
|
}
|
||||||
|
|
||||||
// writePaddingTurnFrames writes one padding turn as a sequence of valid
|
// writePaddingTurnFrames writes one padding turn as a sequence of valid
|
||||||
// Minecraft custom payload frames. Only the framing is native: payload bodies
|
// Minecraft custom payload frames. Only the framing is native: payload bodies
|
||||||
// stay zero-filled, so the captured traffic shape is kept.
|
// stay zero-filled, so the captured traffic shape is kept.
|
||||||
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int, framing paddingFraming) (int, error) {
|
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int) (int, error) {
|
||||||
startDelay, err := randomPaddingDelay(turn.startDelay)
|
startDelay, err := randomPaddingDelay(turn.startDelay)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return 0, fmt.Errorf("select padding start delay: %w", err)
|
return 0, fmt.Errorf("select padding start delay: %w", err)
|
||||||
@@ -321,7 +241,7 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
|
|||||||
}
|
}
|
||||||
|
|
||||||
zeros := make([]byte, maxPaddingFrameDataLength)
|
zeros := make([]byte, maxPaddingFrameDataLength)
|
||||||
channel := String(framing.channel)
|
channel := String(paddingFrameChannel)
|
||||||
written := 0
|
written := 0
|
||||||
for i, chunkLength := range chunks {
|
for i, chunkLength := range chunks {
|
||||||
if i < len(delays) {
|
if i < len(delays) {
|
||||||
@@ -333,12 +253,12 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
|
|||||||
return written, delayErr
|
return written, delayErr
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
frameLengths, planErr := framing.plan(chunkLength)
|
frameLengths, planErr := paddingFramePlan(chunkLength)
|
||||||
if planErr != nil {
|
if planErr != nil {
|
||||||
return written, planErr
|
return written, planErr
|
||||||
}
|
}
|
||||||
for _, frameLength := range frameLengths {
|
for _, frameLength := range frameLengths {
|
||||||
dataLength, ok := framing.frameDataLength(frameLength)
|
dataLength, ok := paddingFrameDataLength(frameLength)
|
||||||
if !ok {
|
if !ok {
|
||||||
return written, fmt.Errorf("unframed padding length %d", frameLength)
|
return written, fmt.Errorf("unframed padding length %d", frameLength)
|
||||||
}
|
}
|
||||||
@@ -352,6 +272,63 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
|
|||||||
return written, nil
|
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) {
|
func selectPaddingVariant(turn paddingTurn, prefixLength int) (int, []int, []paddingDelayRange, error) {
|
||||||
if len(turn.variants) == 0 {
|
if len(turn.variants) == 0 {
|
||||||
minimum, maximum := turn.minLength, turn.maxLength
|
minimum, maximum := turn.minLength, turn.maxLength
|
||||||
|
|||||||
@@ -12,8 +12,8 @@ import (
|
|||||||
|
|
||||||
func TestPaddingFrameDataLengthRoundTrip(t *testing.T) {
|
func TestPaddingFrameDataLengthRoundTrip(t *testing.T) {
|
||||||
for dataLength := 0; dataLength <= maxPaddingFrameDataLength; dataLength++ {
|
for dataLength := 0; dataLength <= maxPaddingFrameDataLength; dataLength++ {
|
||||||
frameLength := defaultPaddingFraming.frameLength(dataLength)
|
frameLength := paddingFrameLength(dataLength)
|
||||||
got, ok := defaultPaddingFraming.frameDataLength(frameLength)
|
got, ok := paddingFrameDataLength(frameLength)
|
||||||
if !ok || got != dataLength {
|
if !ok || got != dataLength {
|
||||||
t.Fatalf("data length %d -> frame %d -> data %d (ok=%v)", dataLength, frameLength, got, ok)
|
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) {
|
func TestPaddingFramePlanTotals(t *testing.T) {
|
||||||
lengths := []int{defaultPaddingFraming.overhead(), defaultPaddingFraming.overhead() + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, defaultPaddingFraming.maxFrameLength() - 1, defaultPaddingFraming.maxFrameLength(), defaultPaddingFraming.maxFrameLength() + 1, 3 * defaultPaddingFraming.maxFrameLength(), 1024 * 1024}
|
lengths := []int{paddingFrameOverhead, paddingFrameOverhead + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, maxPaddingFrameLength - 1, maxPaddingFrameLength, maxPaddingFrameLength + 1, 3 * maxPaddingFrameLength, 1024 * 1024}
|
||||||
for _, length := range lengths {
|
for _, length := range lengths {
|
||||||
plan, err := defaultPaddingFraming.plan(length)
|
plan, err := paddingFramePlan(length)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("plan %d: %v", length, err)
|
t.Fatalf("plan %d: %v", length, err)
|
||||||
}
|
}
|
||||||
total := 0
|
total := 0
|
||||||
for _, frameLength := range plan {
|
for _, frameLength := range plan {
|
||||||
if _, ok := defaultPaddingFraming.frameDataLength(frameLength); !ok {
|
if _, ok := paddingFrameDataLength(frameLength); !ok {
|
||||||
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
|
t.Fatalf("plan %d contains unreachable frame %d", length, frameLength)
|
||||||
}
|
}
|
||||||
if frameLength > defaultPaddingFraming.maxFrameLength() {
|
if frameLength > maxPaddingFrameLength {
|
||||||
t.Fatalf("plan %d contains oversized frame %d", length, frameLength)
|
t.Fatalf("plan %d contains oversized frame %d", length, frameLength)
|
||||||
}
|
}
|
||||||
total += frameLength
|
total += frameLength
|
||||||
@@ -44,11 +44,11 @@ func TestPaddingFramePlanTotals(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPaddingFramePlanRoundsUpShortTurn(t *testing.T) {
|
func TestPaddingFramePlanRoundsUpShortTurn(t *testing.T) {
|
||||||
plan, err := defaultPaddingFraming.plan(2)
|
plan, err := paddingFramePlan(2)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if len(plan) != 1 || plan[0] != defaultPaddingFraming.overhead() {
|
if len(plan) != 1 || plan[0] != paddingFrameOverhead {
|
||||||
t.Fatalf("short turn plan = %v", plan)
|
t.Fatalf("short turn plan = %v", plan)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -57,12 +57,12 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
|
|||||||
turns := []paddingTurn{
|
turns := []paddingTurn{
|
||||||
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
|
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
|
||||||
{direction: paddingClientToServer, minLength: 2, maxLength: 2},
|
{direction: paddingClientToServer, minLength: 2, maxLength: 2},
|
||||||
{direction: paddingClientToServer, minLength: defaultPaddingFraming.maxFrameLength(), maxLength: defaultPaddingFraming.maxFrameLength()},
|
{direction: paddingClientToServer, minLength: maxPaddingFrameLength, maxLength: maxPaddingFrameLength},
|
||||||
{direction: paddingClientToServer, minLength: 3*defaultPaddingFraming.maxFrameLength() + 7, maxLength: 3*defaultPaddingFraming.maxFrameLength() + 7},
|
{direction: paddingClientToServer, minLength: 3*maxPaddingFrameLength + 7, maxLength: 3*maxPaddingFrameLength + 7},
|
||||||
}
|
}
|
||||||
for i, turn := range turns {
|
for i, turn := range turns {
|
||||||
var buffer bytes.Buffer
|
var buffer bytes.Buffer
|
||||||
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationPacketIDs121.serverboundCustomPayload, defaultPaddingFraming)
|
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationServerboundCustomPayload)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("turn %d: %v", i, err)
|
t.Fatalf("turn %d: %v", i, err)
|
||||||
}
|
}
|
||||||
@@ -81,10 +81,10 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("turn %d frame %d is not a valid packet: %v", i, frames, err)
|
t.Fatalf("turn %d frame %d is not a valid packet: %v", i, frames, err)
|
||||||
}
|
}
|
||||||
if packet.packetID != configurationPacketIDs121.serverboundCustomPayload {
|
if packet.packetID != configurationServerboundCustomPayload {
|
||||||
t.Fatalf("turn %d frame %d has packet id %d", i, frames, packet.packetID)
|
t.Fatalf("turn %d frame %d has packet id %d", i, frames, packet.packetID)
|
||||||
}
|
}
|
||||||
_, ok, err := parseCustomPayload(packet, DefaultDataChannel)
|
_, ok, err := parseCustomPayload(packet)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("turn %d frame %d: %v", i, frames, err)
|
t.Fatalf("turn %d frame %d: %v", i, frames, err)
|
||||||
}
|
}
|
||||||
@@ -107,7 +107,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
|
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,7 +119,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("padding stream is not a valid packet stream: %v", err)
|
t.Fatalf("padding stream is not a valid packet stream: %v", err)
|
||||||
}
|
}
|
||||||
if packet.packetID != configurationPacketIDs121.serverboundCustomPayload {
|
if packet.packetID != configurationServerboundCustomPayload {
|
||||||
t.Fatalf("unexpected packet id %d in padding stream", packet.packetID)
|
t.Fatalf("unexpected packet id %d in padding stream", packet.packetID)
|
||||||
}
|
}
|
||||||
total += before - reader.Len()
|
total += before - reader.Len()
|
||||||
@@ -135,7 +135,7 @@ func TestRunPaddingScheduleRejectsInvalidSchedule(t *testing.T) {
|
|||||||
schedule := []paddingTurn{
|
schedule := []paddingTurn{
|
||||||
{direction: paddingServerToClient, minLength: 10, maxLength: 10},
|
{direction: paddingServerToClient, minLength: 10, maxLength: 10},
|
||||||
}
|
}
|
||||||
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err == nil {
|
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause); err == nil {
|
||||||
t.Fatal("expected an error for a prefixed server-to-client first turn")
|
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) {
|
func TestRunPaddingScheduleWithoutTurns(t *testing.T) {
|
||||||
var out bytes.Buffer
|
var out bytes.Buffer
|
||||||
if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
|
if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if out.Len() != 0 {
|
if out.Len() != 0 {
|
||||||
@@ -167,7 +167,7 @@ func TestRunPaddingScheduleStopsWhenClosed(t *testing.T) {
|
|||||||
pauses++
|
pauses++
|
||||||
return net.ErrClosed
|
return net.ErrClosed
|
||||||
}
|
}
|
||||||
err := runPaddingSchedule(&out, true, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121)
|
err := runPaddingSchedule(&out, true, 2, schedule, sleep)
|
||||||
if !errors.Is(err, net.ErrClosed) {
|
if !errors.Is(err, net.ErrClosed) {
|
||||||
t.Fatalf("expected net.ErrClosed, got %v", err)
|
t.Fatalf("expected net.ErrClosed, got %v", err)
|
||||||
}
|
}
|
||||||
@@ -208,7 +208,7 @@ func TestPaddingDelayLeadsIntoTheTurn(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
|
if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return events
|
return events
|
||||||
@@ -246,7 +246,7 @@ func TestPaddingDelayRangeJittersOnlyTheSender(t *testing.T) {
|
|||||||
}
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); err != nil {
|
if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
return pauses
|
return pauses
|
||||||
|
|||||||
@@ -19,16 +19,16 @@ type paddingReader struct {
|
|||||||
// writing. Buffer only the first non-padding packet, then let the caller resume
|
// writing. Buffer only the first non-padding packet, then let the caller resume
|
||||||
// reading the underlying stream. This keeps memory bounded without requiring
|
// reading the underlying stream. This keeps memory bounded without requiring
|
||||||
// matching padding lengths or an extra end-of-padding packet on the wire.
|
// matching padding lengths or an extra end-of-padding packet on the wire.
|
||||||
func newPaddingReader(reader io.Reader, isClient bool, paddingChannel string, packetIDs configurationPacketIDs) io.Reader {
|
func newPaddingReader(reader io.Reader, isClient bool) io.Reader {
|
||||||
first := make(chan paddingReadResult, 1)
|
first := make(chan paddingReadResult, 1)
|
||||||
go func() {
|
go func() {
|
||||||
frame, err := readPastPadding(reader, paddingFramePacketID(packetIDs, !isClient), paddingChannel)
|
frame, err := readPastPadding(reader, paddingFramePacketID(!isClient))
|
||||||
first <- paddingReadResult{frame: frame, err: err}
|
first <- paddingReadResult{frame: frame, err: err}
|
||||||
}()
|
}()
|
||||||
return &paddingReader{reader: reader, first: first}
|
return &paddingReader{reader: reader, first: first}
|
||||||
}
|
}
|
||||||
|
|
||||||
func readPastPadding(reader io.Reader, packetID int, paddingChannel string) ([]byte, error) {
|
func readPastPadding(reader io.Reader, packetID int) ([]byte, error) {
|
||||||
for {
|
for {
|
||||||
packet, err := readPacket(reader)
|
packet, err := readPacket(reader)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -36,7 +36,7 @@ func readPastPadding(reader io.Reader, packetID int, paddingChannel string) ([]b
|
|||||||
}
|
}
|
||||||
if packet.packetID == packetID {
|
if packet.packetID == packetID {
|
||||||
var channel String
|
var channel String
|
||||||
if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && string(channel) == paddingChannel {
|
if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && channel == paddingFrameChannel {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,9 +10,9 @@ import (
|
|||||||
|
|
||||||
func TestPaddingReaderPreservesFollowingPackets(t *testing.T) {
|
func TestPaddingReaderPreservesFollowingPackets(t *testing.T) {
|
||||||
for _, isClient := range []bool{true, false} {
|
for _, isClient := range []bool{true, false} {
|
||||||
packetID := paddingFramePacketID(configurationPacketIDs121, !isClient)
|
packetID := paddingFramePacketID(!isClient)
|
||||||
var wire bytes.Buffer
|
var wire bytes.Buffer
|
||||||
paddingChannel := String(DefaultPaddingChannel)
|
paddingChannel := String(paddingFrameChannel)
|
||||||
padding := RestBytes(make([]byte, 1024))
|
padding := RestBytes(make([]byte, 1024))
|
||||||
if err := writePacket(&wire, packetID, &paddingChannel, &padding); err != nil {
|
if err := writePacket(&wire, packetID, &paddingChannel, &padding); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -24,15 +24,15 @@ func TestPaddingReaderPreservesFollowingPackets(t *testing.T) {
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
id := Long(42)
|
id := Long(42)
|
||||||
if err := writePacket(&want, configurationPacketIDs121.clientboundKeepAlive, &id); err != nil {
|
if err := writePacket(&want, configurationKeepAlive, &id); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
channel := String(DefaultDataChannel)
|
channel := String(packetChannel)
|
||||||
if err := writePacket(&want, packetID, &channel, &payload); err != nil {
|
if err := writePacket(&want, packetID, &channel, &payload); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
wire.Write(want.Bytes())
|
wire.Write(want.Bytes())
|
||||||
got, err := io.ReadAll(newPaddingReader(&wire, isClient, DefaultPaddingChannel, configurationPacketIDs121))
|
got, err := io.ReadAll(newPaddingReader(&wire, isClient))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
@@ -52,7 +52,7 @@ func TestPaddingReaderReadErrors(t *testing.T) {
|
|||||||
{name: "truncated", wire: []byte{2, 1}, err: io.ErrUnexpectedEOF},
|
{name: "truncated", wire: []byte{2, 1}, err: io.ErrUnexpectedEOF},
|
||||||
} {
|
} {
|
||||||
t.Run(test.name, func(t *testing.T) {
|
t.Run(test.name, func(t *testing.T) {
|
||||||
reader := newPaddingReader(bytes.NewReader(test.wire), true, DefaultPaddingChannel, configurationPacketIDs121)
|
reader := newPaddingReader(bytes.NewReader(test.wire), true)
|
||||||
if _, err := reader.Read(make([]byte, 1)); !errors.Is(err, test.err) {
|
if _, err := reader.Read(make([]byte, 1)); !errors.Is(err, test.err) {
|
||||||
t.Fatalf("got %v, want %v", 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) {
|
func TestPaddingReaderUnblocksOnClose(t *testing.T) {
|
||||||
client, server := net.Pipe()
|
client, server := net.Pipe()
|
||||||
defer server.Close()
|
defer server.Close()
|
||||||
reader := newPaddingReader(client, true, DefaultPaddingChannel, configurationPacketIDs121)
|
reader := newPaddingReader(client, true)
|
||||||
if n, err := reader.Read(nil); n != 0 || err != nil {
|
if n, err := reader.Read(nil); n != 0 || err != nil {
|
||||||
t.Fatalf("empty read = %d, %v", n, err)
|
t.Fatalf("empty read = %d, %v", n, err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -184,18 +184,19 @@ func propertyListFromYggdrasil(properties []yggdrasilProperty) loginProperties {
|
|||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
// writeLoginFinished writes the Login Finished packet. From 26.2 on the packet
|
func readLoginSuccess(packet *mcPacket) (loginProfile, error) {
|
||||||
// also carries the connection session id, which the client only uses for its
|
var (
|
||||||
// own telemetry, so one value per process is enough.
|
profile loginProfile
|
||||||
func writeLoginFinished(w io.Writer, version protocolVersion, profile loginProfile) error {
|
username String
|
||||||
username := String(profile.Username)
|
)
|
||||||
fields := []field{&profile.UUID, &username, &profile.Properties}
|
if err := packet.readFields(&profile.UUID, &username, &profile.Properties); err != nil {
|
||||||
if version.loginFinishedSessionID {
|
return loginProfile{}, err
|
||||||
sessionID, err := serverSessionID()
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
fields = append(fields, &sessionID)
|
|
||||||
}
|
}
|
||||||
return writePacket(w, version.login.clientboundLoginFinished, fields...)
|
profile.Username = string(username)
|
||||||
|
return profile, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func writeLoginSuccess(w io.Writer, profile loginProfile) error {
|
||||||
|
username := String(profile.Username)
|
||||||
|
return writePacket(w, 0x02, &profile.UUID, &username, &profile.Properties)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -238,29 +238,6 @@ func (v *UnsignedShort) writeTo(w io.Writer) error {
|
|||||||
return nil
|
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
|
type Long int64
|
||||||
|
|
||||||
func (v *Long) readFrom(r io.Reader) error {
|
func (v *Long) readFrom(r io.Reader) error {
|
||||||
@@ -466,6 +443,6 @@ func writeFull(w io.Writer, p []byte) error {
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func writeDisconnectPacket(w io.Writer, packetID int, reason string) error {
|
func writeDisconnectPacket(w io.Writer, reason string) error {
|
||||||
return writePacket(w, packetID, new(String(reason)))
|
return writePacket(w, 0x00, new(String(reason)))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,154 +0,0 @@
|
|||||||
// Status probe used to pick the protocol version of the peer.
|
|
||||||
package xmc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
|
||||||
"strconv"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
xnet "github.com/xtls/xray-core/common/net"
|
|
||||||
"github.com/xtls/xray-core/transport/internet/finalmask"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
// protocolProbeTimeout bounds one status round trip. A peer that cannot
|
|
||||||
// answer status in this time is not going to answer the login either.
|
|
||||||
protocolProbeTimeout = 5 * time.Second
|
|
||||||
// protocolProbeTTL keeps detection off the connection path: a real client
|
|
||||||
// refreshes a server's status in its server list, not once per join.
|
|
||||||
protocolProbeTTL = 10 * time.Minute
|
|
||||||
// maxProtocolProbeEntries bounds the cache. A proxy can dial many different
|
|
||||||
// destinations, and each entry is three words.
|
|
||||||
maxProtocolProbeEntries = 256
|
|
||||||
)
|
|
||||||
|
|
||||||
// statusVersion is the part of the status JSON the probe reads. Vanilla reports
|
|
||||||
// its own protocol version there, and the login it accepts is that version.
|
|
||||||
type statusVersion struct {
|
|
||||||
Version struct {
|
|
||||||
Name string `json:"name"`
|
|
||||||
Protocol int32 `json:"protocol"`
|
|
||||||
} `json:"version"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type protocolProbeEntry struct {
|
|
||||||
number Varint
|
|
||||||
name string
|
|
||||||
expires time.Time
|
|
||||||
}
|
|
||||||
|
|
||||||
var protocolProbeCache = struct {
|
|
||||||
mu sync.Mutex
|
|
||||||
entries map[string]protocolProbeEntry
|
|
||||||
}{entries: make(map[string]protocolProbeEntry)}
|
|
||||||
|
|
||||||
// probeProtocolVersion asks the peer for its status and returns the protocol
|
|
||||||
// number and release name it reports.
|
|
||||||
//
|
|
||||||
// The probe is a second TCP connection to the same destination, exactly what a
|
|
||||||
// client does when it refreshes a server in its list, so the peer sees nothing
|
|
||||||
// unusual. It only works when the destination speaks plain Minecraft: for a
|
|
||||||
// destination behind another transport, set protocol_version instead.
|
|
||||||
func probeProtocolVersion(dest *xnet.Destination, hostname string, dialer *finalmask.Dialer) (Varint, string, error) {
|
|
||||||
if dest == nil {
|
|
||||||
return 0, "", fmt.Errorf("status probe: no destination")
|
|
||||||
}
|
|
||||||
if dialer == nil || dialer.DialTCP == nil {
|
|
||||||
return 0, "", fmt.Errorf("status probe: no TCP dialer")
|
|
||||||
}
|
|
||||||
|
|
||||||
conn, err := dialer.DialTCP(*dest)
|
|
||||||
if err != nil {
|
|
||||||
return 0, "", fmt.Errorf("status probe: dial: %w", err)
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
if err := conn.SetDeadline(time.Now().Add(protocolProbeTimeout)); err != nil {
|
|
||||||
return 0, "", fmt.Errorf("status probe: set deadline: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
address := String(hostname)
|
|
||||||
if address == "" {
|
|
||||||
address = String(dest.Address.String())
|
|
||||||
}
|
|
||||||
var (
|
|
||||||
protocolNumber Varint = latestProtocolVersion.number
|
|
||||||
port UnsignedShort = UnsignedShort(dest.Port.Value())
|
|
||||||
nextState Varint = 1 // status
|
|
||||||
)
|
|
||||||
if err := writePacket(conn, handshakeServerboundIntention, &protocolNumber, &address, &port, &nextState); err != nil {
|
|
||||||
return 0, "", fmt.Errorf("status probe: write handshake: %w", err)
|
|
||||||
}
|
|
||||||
if err := writePacket(conn, statusServerboundRequest); err != nil {
|
|
||||||
return 0, "", fmt.Errorf("status probe: write status request: %w", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
packet, err := readPacket(conn)
|
|
||||||
if err != nil {
|
|
||||||
return 0, "", fmt.Errorf("status probe: read status response: %w", err)
|
|
||||||
}
|
|
||||||
if packet.packetID != statusClientboundResponse {
|
|
||||||
return 0, "", fmt.Errorf("status probe: unexpected status packet id: 0x%02x", packet.packetID)
|
|
||||||
}
|
|
||||||
var payload String
|
|
||||||
if err := packet.readFields(&payload); err != nil {
|
|
||||||
return 0, "", fmt.Errorf("status probe: read status payload: %w", err)
|
|
||||||
}
|
|
||||||
var status statusVersion
|
|
||||||
if err := json.Unmarshal([]byte(payload), &status); err != nil {
|
|
||||||
return 0, "", fmt.Errorf("status probe: decode status response: %w", err)
|
|
||||||
}
|
|
||||||
if status.Version.Protocol <= 0 {
|
|
||||||
return 0, "", fmt.Errorf("status probe: status response has no version")
|
|
||||||
}
|
|
||||||
return Varint(status.Version.Protocol), status.Version.Name, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// detectProtocolVersion returns the peer's protocol version, reusing a recent
|
|
||||||
// probe for the same destination.
|
|
||||||
func detectProtocolVersion(dest *xnet.Destination, hostname string, dialer *finalmask.Dialer) (Varint, string, error) {
|
|
||||||
key := protocolProbeKey(dest)
|
|
||||||
now := time.Now()
|
|
||||||
|
|
||||||
protocolProbeCache.mu.Lock()
|
|
||||||
if entry, ok := protocolProbeCache.entries[key]; ok && entry.expires.After(now) {
|
|
||||||
protocolProbeCache.mu.Unlock()
|
|
||||||
return entry.number, entry.name, nil
|
|
||||||
}
|
|
||||||
protocolProbeCache.mu.Unlock()
|
|
||||||
|
|
||||||
number, name, err := probeProtocolVersion(dest, hostname, dialer)
|
|
||||||
if err != nil {
|
|
||||||
return 0, "", err
|
|
||||||
}
|
|
||||||
|
|
||||||
protocolProbeCache.mu.Lock()
|
|
||||||
if len(protocolProbeCache.entries) >= maxProtocolProbeEntries {
|
|
||||||
for cachedKey, entry := range protocolProbeCache.entries {
|
|
||||||
if entry.expires.Before(now) {
|
|
||||||
delete(protocolProbeCache.entries, cachedKey)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if len(protocolProbeCache.entries) >= maxProtocolProbeEntries {
|
|
||||||
clear(protocolProbeCache.entries)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
protocolProbeCache.entries[key] = protocolProbeEntry{number: number, name: name, expires: now.Add(protocolProbeTTL)}
|
|
||||||
protocolProbeCache.mu.Unlock()
|
|
||||||
return number, name, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// forgetProbedVersions drops every cached detection. A login rejected with a
|
|
||||||
// version mismatch means the cached row is stale (the peer was upgraded, or the
|
|
||||||
// detection was wrong), so the next attempt has to ask again instead of waiting
|
|
||||||
// for the TTL.
|
|
||||||
func forgetProbedVersions() {
|
|
||||||
protocolProbeCache.mu.Lock()
|
|
||||||
clear(protocolProbeCache.entries)
|
|
||||||
protocolProbeCache.mu.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func protocolProbeKey(dest *xnet.Destination) string {
|
|
||||||
return dest.Network.String() + "|" + dest.Address.String() + "|" + strconv.Itoa(int(dest.Port.Value()))
|
|
||||||
}
|
|
||||||
@@ -1,251 +0,0 @@
|
|||||||
package xmc
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
"net"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
"testing"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
xnet "github.com/xtls/xray-core/common/net"
|
|
||||||
"github.com/xtls/xray-core/transport/internet/finalmask"
|
|
||||||
)
|
|
||||||
|
|
||||||
// statusTestServer answers exactly one status exchange with the given version.
|
|
||||||
func statusTestServer(t *testing.T, listener net.Listener, protocol int32, name string) {
|
|
||||||
t.Helper()
|
|
||||||
go func() {
|
|
||||||
conn, err := listener.Accept()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
|
|
||||||
if _, err := readPacket(conn); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
if _, err := readPacket(conn); err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
payload := String(fmt.Sprintf(`{"description":"test","players":{"max":0,"online":0},"version":{"name":%q,"protocol":%d}}`, name, protocol))
|
|
||||||
_ = writePacket(conn, statusClientboundResponse, &payload)
|
|
||||||
}()
|
|
||||||
}
|
|
||||||
|
|
||||||
func statusTestDestination(t *testing.T, listener net.Listener) xnet.Destination {
|
|
||||||
t.Helper()
|
|
||||||
dest, err := xnet.ParseDestination("tcp:" + listener.Addr().String())
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
return dest
|
|
||||||
}
|
|
||||||
|
|
||||||
func statusTestDialer(dialErr error) *finalmask.Dialer {
|
|
||||||
return &finalmask.Dialer{DialTCP: func(dest xnet.Destination) (net.Conn, error) {
|
|
||||||
if dialErr != nil {
|
|
||||||
return nil, dialErr
|
|
||||||
}
|
|
||||||
return net.Dial("tcp", net.JoinHostPort(dest.Address.String(), strconv.Itoa(int(dest.Port.Value()))))
|
|
||||||
}}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestProbeProtocolVersion reads the version out of the status response, which
|
|
||||||
// is the version the peer's login expects.
|
|
||||||
func TestProbeProtocolVersion(t *testing.T) {
|
|
||||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer listener.Close()
|
|
||||||
statusTestServer(t, listener, 767, "1.21.1")
|
|
||||||
|
|
||||||
dest := statusTestDestination(t, listener)
|
|
||||||
number, name, err := probeProtocolVersion(&dest, "localhost", statusTestDialer(nil))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("probe: %v", err)
|
|
||||||
}
|
|
||||||
if number != 767 || name != "1.21.1" {
|
|
||||||
t.Fatalf("probe = %d %q, want 767 \"1.21.1\"", number, name)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestProbeProtocolVersionRejectsBrokenPeer(t *testing.T) {
|
|
||||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer listener.Close()
|
|
||||||
go func() {
|
|
||||||
conn, err := listener.Accept()
|
|
||||||
if err != nil {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer conn.Close()
|
|
||||||
_ = conn.SetDeadline(time.Now().Add(5 * time.Second))
|
|
||||||
_, _ = readPacket(conn)
|
|
||||||
_, _ = readPacket(conn)
|
|
||||||
payload := String(`{"description":"no version here"}`)
|
|
||||||
_ = writePacket(conn, statusClientboundResponse, &payload)
|
|
||||||
}()
|
|
||||||
|
|
||||||
dest := statusTestDestination(t, listener)
|
|
||||||
if _, _, err := probeProtocolVersion(&dest, "localhost", statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "no version") {
|
|
||||||
t.Fatalf("probe error = %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
if _, _, err := probeProtocolVersion(&dest, "localhost", nil); err == nil || !strings.Contains(err.Error(), "no TCP dialer") {
|
|
||||||
t.Fatalf("nil dialer error = %v", err)
|
|
||||||
}
|
|
||||||
if _, _, err := probeProtocolVersion(nil, "localhost", statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "no destination") {
|
|
||||||
t.Fatalf("nil destination error = %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestDetectProtocolVersionCaches checks a destination is probed once per TTL:
|
|
||||||
// the second call must answer from the cache even though dialing now fails.
|
|
||||||
func TestDetectProtocolVersionCaches(t *testing.T) {
|
|
||||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
statusTestServer(t, listener, 776, "26.2")
|
|
||||||
dest := statusTestDestination(t, listener)
|
|
||||||
|
|
||||||
number, name, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(nil))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("detect: %v", err)
|
|
||||||
}
|
|
||||||
if number != 776 || name != "26.2" {
|
|
||||||
t.Fatalf("detect = %d %q", number, name)
|
|
||||||
}
|
|
||||||
if err := listener.Close(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
number, _, err = detectProtocolVersion(&dest, "localhost", statusTestDialer(fmt.Errorf("must not dial")))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("cached detect: %v", err)
|
|
||||||
}
|
|
||||||
if number != 776 {
|
|
||||||
t.Fatalf("cached detect = %d", number)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestClientProtocol covers the three ways the client picks its row: a
|
|
||||||
// configured version, a detected one, and the fallback when the peer does not
|
|
||||||
// answer status.
|
|
||||||
func TestClientProtocol(t *testing.T) {
|
|
||||||
t.Run("configured", func(t *testing.T) {
|
|
||||||
// No destination and no dialer: a configured version must not probe.
|
|
||||||
version, err := (&Config{ProtocolVersion: 775}).clientProtocol(nil, nil)
|
|
||||||
if err != nil || version.number != 775 {
|
|
||||||
t.Fatalf("configured = %v, %v", version.number, err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("detected", func(t *testing.T) {
|
|
||||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer listener.Close()
|
|
||||||
statusTestServer(t, listener, 767, "1.21.1")
|
|
||||||
dest := statusTestDestination(t, listener)
|
|
||||||
|
|
||||||
version, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil))
|
|
||||||
if err != nil || version.number != 767 || version.name != "1.21.1" {
|
|
||||||
t.Fatalf("detected = %v %q, %v", version.number, version.name, err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("unknown", func(t *testing.T) {
|
|
||||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer listener.Close()
|
|
||||||
statusTestServer(t, listener, 999, "999")
|
|
||||||
dest := statusTestDestination(t, listener)
|
|
||||||
|
|
||||||
if _, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "not in the supported table") {
|
|
||||||
t.Fatalf("unknown version error = %v", err)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
t.Run("probe failure falls back to the newest row", func(t *testing.T) {
|
|
||||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
address := listener.Addr().String()
|
|
||||||
if err := listener.Close(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
dest, err := xnet.ParseDestination("tcp:" + address)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
|
|
||||||
version, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil))
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("fallback: %v", err)
|
|
||||||
}
|
|
||||||
if version.number != latestProtocolVersion.number {
|
|
||||||
t.Fatalf("fallback version = %d, want %d", version.number, latestProtocolVersion.number)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
// TestForgetProbedVersions covers a stale detection: after a version mismatch
|
|
||||||
// the cache is dropped, so the next connection probes again instead of reusing
|
|
||||||
// the row the peer no longer speaks.
|
|
||||||
func TestForgetProbedVersions(t *testing.T) {
|
|
||||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
statusTestServer(t, listener, 767, "1.21.1")
|
|
||||||
dest := statusTestDestination(t, listener)
|
|
||||||
|
|
||||||
if number, _, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(nil)); err != nil || number != 767 {
|
|
||||||
t.Fatalf("detect = %v, %v", number, err)
|
|
||||||
}
|
|
||||||
forgetProbedVersions()
|
|
||||||
|
|
||||||
// The peer now reports another version; a cached answer would hide it.
|
|
||||||
listener2, err := net.Listen("tcp", "127.0.0.1:0")
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
defer listener2.Close()
|
|
||||||
statusTestServer(t, listener2, 775, "26.1")
|
|
||||||
dest2 := statusTestDestination(t, listener2)
|
|
||||||
|
|
||||||
// A dialer that fails proves the cache was consulted; after forgetting, the
|
|
||||||
// same destination must probe again.
|
|
||||||
if err := listener.Close(); err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if number, _, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(fmt.Errorf("must probe again"))); err == nil {
|
|
||||||
t.Fatalf("stale cache was reused: %v", number)
|
|
||||||
}
|
|
||||||
if number, _, err := detectProtocolVersion(&dest2, "localhost", statusTestDialer(nil)); err != nil || number != 775 {
|
|
||||||
t.Fatalf("fresh detect = %v, %v", number, err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestIsProtocolVersionReject(t *testing.T) {
|
|
||||||
for _, reason := range []string{
|
|
||||||
`{"translate":"multiplayer.disconnect.incompatible","with":["26.3"]}`,
|
|
||||||
`{"translate":"multiplayer.disconnect.outdated_client","with":["26.3"]}`,
|
|
||||||
} {
|
|
||||||
if !isProtocolVersionReject(reason) {
|
|
||||||
t.Fatalf("%s should be a version reject", reason)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if isProtocolVersionReject(`{"translate":"multiplayer.disconnect.not_whitelisted"}`) {
|
|
||||||
t.Fatal("a whitelist reject is not a version reject")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,210 +0,0 @@
|
|||||||
// 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)
|
|
||||||
}
|
|
||||||
@@ -1,165 +0,0 @@
|
|||||||
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,6 +2,7 @@ package xmc
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bufio"
|
"bufio"
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"crypto/rand"
|
"crypto/rand"
|
||||||
"crypto/rsa"
|
"crypto/rsa"
|
||||||
@@ -23,22 +24,12 @@ const (
|
|||||||
// still missing, instead of making every login wait a fixed interval.
|
// still missing, instead of making every login wait a fixed interval.
|
||||||
yggdrasilVerifyFirstPoll = 10 * time.Millisecond
|
yggdrasilVerifyFirstPoll = 10 * time.Millisecond
|
||||||
yggdrasilVerifyMaxPoll = 200 * 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")
|
var errYggdrasilNotJoined = errors.New("player did not join the minecraft session")
|
||||||
|
|
||||||
// serverSessionID is the connection session id that Login Finished carries from
|
// Response by vanilla 26.1.2 server.
|
||||||
// 26.2 on. Vanilla generates it once per server rather than per connection, so
|
var statusResponse = `{"description":"A Minecraft Server","players":{"max":20,"online":0},"version":{"name":"26.1.2","protocol":775},"enforcesSecureChat":true}`
|
||||||
// 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
|
type serverState int
|
||||||
|
|
||||||
@@ -54,10 +45,6 @@ type serverConn struct {
|
|||||||
|
|
||||||
state serverState
|
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
|
handshakeLock sync.Mutex
|
||||||
lifecycleMu sync.Mutex
|
lifecycleMu sync.Mutex
|
||||||
closed bool
|
closed bool
|
||||||
@@ -65,11 +52,9 @@ type serverConn struct {
|
|||||||
password string
|
password string
|
||||||
rsaPrivateKey *rsa.PrivateKey
|
rsaPrivateKey *rsa.PrivateKey
|
||||||
rsaPublicKey []byte
|
rsaPublicKey []byte
|
||||||
dataChannel string
|
|
||||||
paddingChannel string
|
|
||||||
yggdrasil *yggdrasilVerifier
|
yggdrasil *yggdrasilVerifier
|
||||||
paddingSchedule []paddingTurn
|
paddingSchedule []paddingTurn
|
||||||
packet *tickStream
|
packet *packetStream
|
||||||
deadlines *connectionDeadlines
|
deadlines *connectionDeadlines
|
||||||
|
|
||||||
done chan struct{}
|
done chan struct{}
|
||||||
@@ -90,10 +75,10 @@ func (c *serverConn) handshake() error {
|
|||||||
defer func() { _ = c.deadlines.endHandshake() }()
|
defer func() { _ = c.deadlines.endHandshake() }()
|
||||||
|
|
||||||
var (
|
var (
|
||||||
protocolNumber Varint
|
protocolVersion Varint
|
||||||
serverAddress String
|
serverAddress String
|
||||||
serverPort UnsignedShort
|
serverPort UnsignedShort
|
||||||
nextState Varint
|
nextState Varint
|
||||||
)
|
)
|
||||||
|
|
||||||
// handshake packet
|
// handshake packet
|
||||||
@@ -103,11 +88,11 @@ func (c *serverConn) handshake() error {
|
|||||||
return fmt.Errorf("read handshake packet: %w", err)
|
return fmt.Errorf("read handshake packet: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if pkt.packetID != handshakeServerboundIntention {
|
if pkt.packetID != 0 {
|
||||||
return fmt.Errorf("bad handshake packet id")
|
return fmt.Errorf("bad handshake packet id")
|
||||||
}
|
}
|
||||||
|
|
||||||
err = pkt.readFields(&protocolNumber, &serverAddress, &serverPort, &nextState)
|
err = pkt.readFields(&protocolVersion, &serverAddress, &serverPort, &nextState)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("read handshake packet: %w", err)
|
return fmt.Errorf("read handshake packet: %w", err)
|
||||||
}
|
}
|
||||||
@@ -125,14 +110,14 @@ func (c *serverConn) handshake() error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
switch pkt.packetID {
|
switch pkt.packetID {
|
||||||
case statusServerboundRequest: // Status Request
|
case 0: // Status Request
|
||||||
|
|
||||||
err = writePacket(c.writer, statusClientboundResponse, new(String(statusResponse(latestProtocolVersion))))
|
err = writePacket(c.writer, 0, new(String(statusResponse)))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("write status response: %w", err)
|
return fmt.Errorf("write status response: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
case statusServerboundPing: // Ping
|
case 1: // Ping
|
||||||
|
|
||||||
var payload Long
|
var payload Long
|
||||||
err = pkt.readFields(&payload)
|
err = pkt.readFields(&payload)
|
||||||
@@ -140,7 +125,7 @@ func (c *serverConn) handshake() error {
|
|||||||
return fmt.Errorf("read ping packet: %w", err)
|
return fmt.Errorf("read ping packet: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = writePacket(c.writer, statusClientboundPong, &payload)
|
err = writePacket(c.writer, 1, &payload)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return fmt.Errorf("write ping response: %w", err)
|
return fmt.Errorf("write ping response: %w", err)
|
||||||
}
|
}
|
||||||
@@ -151,34 +136,167 @@ func (c *serverConn) handshake() error {
|
|||||||
|
|
||||||
return fmt.Errorf("ping")
|
return fmt.Errorf("ping")
|
||||||
|
|
||||||
case 2, 3:
|
case 2:
|
||||||
|
|
||||||
// Login. A vanilla server starts the login protocol, checks the version
|
// Login
|
||||||
// against its own, and only then reads Login Start; TRANSFER shares the
|
|
||||||
// login but is only accepted when the server allows transfers, which the
|
// login start
|
||||||
// mask does not.
|
|
||||||
if nextState == 3 {
|
pkt, err := readPacket(c.reader)
|
||||||
reason := `{"translate":"multiplayer.disconnect.transfers_disabled"}`
|
if err != nil {
|
||||||
_ = writePacket(c.writer, latestProtocolVersion.login.clientboundLoginDisconnect, new(String(reason)))
|
return fmt.Errorf("read login start packet: %w", err)
|
||||||
return fmt.Errorf("transfers are disabled")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// The version picks the row, not the other way around: the ids are the
|
if pkt.packetID != 0 {
|
||||||
// registration order of the peer's own protocol, so the client decides.
|
return fmt.Errorf("bad login start packet id")
|
||||||
// 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
|
|
||||||
|
|
||||||
if err = c.login(); err != nil {
|
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 {
|
||||||
return err
|
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
|
return nil
|
||||||
|
|
||||||
default:
|
default:
|
||||||
@@ -186,222 +304,6 @@ 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) {
|
func (c *serverConn) verifyYggdrasilLogin(username string, uuid UUID, serverID string) (loginProfile, error) {
|
||||||
ctx, cancel := context.WithTimeout(context.Background(), yggdrasilVerifyTimeout)
|
ctx, cancel := context.WithTimeout(context.Background(), yggdrasilVerifyTimeout)
|
||||||
defer cancel()
|
defer cancel()
|
||||||
@@ -446,8 +348,8 @@ func (c *serverConn) verifyYggdrasilLogin(username string, uuid UUID, serverID s
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func validateLoginAcknowledgedPacket(pkt *mcPacket, packetID int) error {
|
func validateLoginAcknowledgedPacket(pkt *mcPacket) error {
|
||||||
if pkt.packetID != packetID {
|
if pkt.packetID != 0x03 {
|
||||||
return fmt.Errorf("bad login acknowledged packet id: %d", pkt.packetID)
|
return fmt.Errorf("bad login acknowledged packet id: %d", pkt.packetID)
|
||||||
}
|
}
|
||||||
if len(pkt.data) != 0 {
|
if len(pkt.data) != 0 {
|
||||||
@@ -481,10 +383,6 @@ func (c *serverConn) Close() error {
|
|||||||
c.lifecycleMu.Unlock()
|
c.lifecycleMu.Unlock()
|
||||||
c.closeOnce.Do(func() { close(c.done) })
|
c.closeOnce.Do(func() { close(c.done) })
|
||||||
if packet != nil {
|
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()
|
packet.Stop()
|
||||||
}
|
}
|
||||||
return c.c.Close()
|
return c.c.Close()
|
||||||
@@ -515,7 +413,7 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error {
|
|||||||
return c.deadlines.setWriteDeadline(t)
|
return c.deadlines.setWriteDeadline(t)
|
||||||
}
|
}
|
||||||
|
|
||||||
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier, dataChannel, paddingChannel string) (*serverConn, error) {
|
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier) (*serverConn, error) {
|
||||||
if len(profiles) == 0 && yggdrasil == nil {
|
if len(profiles) == 0 && yggdrasil == nil {
|
||||||
return nil, fmt.Errorf("empty profiles")
|
return nil, fmt.Errorf("empty profiles")
|
||||||
}
|
}
|
||||||
@@ -539,8 +437,6 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
|
|||||||
password: password,
|
password: password,
|
||||||
rsaPrivateKey: rsaPrivateKey,
|
rsaPrivateKey: rsaPrivateKey,
|
||||||
rsaPublicKey: rsaPublicKey,
|
rsaPublicKey: rsaPublicKey,
|
||||||
dataChannel: dataChannel,
|
|
||||||
paddingChannel: paddingChannel,
|
|
||||||
yggdrasil: yggdrasil,
|
yggdrasil: yggdrasil,
|
||||||
paddingSchedule: paddingSchedule,
|
paddingSchedule: paddingSchedule,
|
||||||
deadlines: newConnectionDeadlines(c),
|
deadlines: newConnectionDeadlines(c),
|
||||||
|
|||||||
@@ -17,9 +17,9 @@ type cryptoStream struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func newCryptoReader(r io.Reader, sharedSecret []byte) (*cryptoStream, error) {
|
func newCryptoReader(r io.Reader, sharedSecret []byte) (*cryptoStream, error) {
|
||||||
blockCipher, err := newAESCipher(sharedSecret)
|
blockCipher, err := aes.NewCipher(sharedSecret)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("new aes cipher: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
stream := newCFB8Decrypt(blockCipher, sharedSecret)
|
stream := newCFB8Decrypt(blockCipher, sharedSecret)
|
||||||
@@ -27,27 +27,6 @@ func newCryptoReader(r io.Reader, sharedSecret []byte) (*cryptoStream, error) {
|
|||||||
return &cryptoStream{stream: stream, r: r}, nil
|
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) {
|
func (c *cryptoStream) Read(b []byte) (int, error) {
|
||||||
if c.r == nil {
|
if c.r == nil {
|
||||||
panic("read on a write-only crypto stream")
|
panic("read on a write-only crypto stream")
|
||||||
@@ -71,9 +50,9 @@ func (c *cryptoStream) Read(b []byte) (int, error) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func newCryptoWriter(w io.Writer, sharedSecret []byte) (*cryptoStream, error) {
|
func newCryptoWriter(w io.Writer, sharedSecret []byte) (*cryptoStream, error) {
|
||||||
blockCipher, err := newAESCipher(sharedSecret)
|
blockCipher, err := aes.NewCipher(sharedSecret)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, fmt.Errorf("new aes cipher: %w", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
stream := newCFB8Encrypt(blockCipher, sharedSecret)
|
stream := newCFB8Encrypt(blockCipher, sharedSecret)
|
||||||
|
|||||||
@@ -1,209 +0,0 @@
|
|||||||
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,14 +468,6 @@ type yggdrasilAuth struct {
|
|||||||
|
|
||||||
keyMu sync.Mutex
|
keyMu sync.Mutex
|
||||||
signatureKey *rsa.PublicKey
|
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 {
|
func newYggdrasilAuth(config *yggdrasilConfig) *yggdrasilAuth {
|
||||||
|
|||||||
@@ -58,15 +58,6 @@ type fakeYggdrasil struct {
|
|||||||
|
|
||||||
boundProfile string
|
boundProfile string
|
||||||
joined map[string]string // serverId -> profile name
|
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) {
|
func writeFakeYggdrasilJSON(w http.ResponseWriter, status int, body string) {
|
||||||
@@ -133,30 +124,15 @@ func newFakeYggdrasilHandler(state *fakeYggdrasil) http.Handler {
|
|||||||
state.joinCalls++
|
state.joinCalls++
|
||||||
state.boundProfile = request.SelectedProfile
|
state.boundProfile = request.SelectedProfile
|
||||||
state.joined[request.ServerID] = state.profile.Name
|
state.joined[request.ServerID] = state.profile.Name
|
||||||
state.latestServerID = request.ServerID
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
})
|
})
|
||||||
|
|
||||||
mux.HandleFunc(prefix+"/sessionserver/session/minecraft/hasJoined", func(w http.ResponseWriter, r *http.Request) {
|
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()
|
state.mu.Lock()
|
||||||
defer state.mu.Unlock()
|
defer state.mu.Unlock()
|
||||||
|
|
||||||
if state.singleSession && state.latestServerID != serverID {
|
name, found := state.joined[r.URL.Query().Get("serverId")]
|
||||||
w.WriteHeader(http.StatusNoContent)
|
if !found || name != r.URL.Query().Get("username") {
|
||||||
return
|
|
||||||
}
|
|
||||||
name, found := state.joined[serverID]
|
|
||||||
if !found || name != username {
|
|
||||||
w.WriteHeader(http.StatusNoContent)
|
w.WriteHeader(http.StatusNoContent)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -382,14 +358,11 @@ func TestHandshakeWithYggdrasil(t *testing.T) {
|
|||||||
t.Errorf("new verifier: %v", err)
|
t.Errorf("new verifier: %v", err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel)
|
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("wrap server: %v", err)
|
t.Errorf("wrap server: %v", err)
|
||||||
return
|
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)
|
buf := make([]byte, 1024)
|
||||||
n, err := server.Read(buf)
|
n, err := server.Read(buf)
|
||||||
@@ -414,7 +387,7 @@ func TestHandshakeWithYggdrasil(t *testing.T) {
|
|||||||
|
|
||||||
// The client intentionally has no pinned server key: Yggdrasil mode accepts
|
// The client intentionally has no pinned server key: Yggdrasil mode accepts
|
||||||
// the key sent by the server and binds it through the session hash.
|
// the key sent by the server and binds it through the session hash.
|
||||||
client, err := newClientConn(rawClient, latestProtocolVersion, nil, password, nil, "localhost", nil, newTestYggdrasilAuth(t, api, "SkinUser"), DefaultDataChannel, DefaultPaddingChannel)
|
client, err := newClientConn(rawClient, nil, password, nil, "localhost", nil, newTestYggdrasilAuth(t, api, "SkinUser"))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("new client: %v", err)
|
t.Fatalf("new client: %v", err)
|
||||||
}
|
}
|
||||||
@@ -448,128 +421,6 @@ 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) {
|
func TestYggdrasilVerifiesTexturesSignature(t *testing.T) {
|
||||||
state, api := newFakeYggdrasilServer(t)
|
state, api := newFakeYggdrasilServer(t)
|
||||||
auth := newTestYggdrasilAuth(t, api, "SkinUser")
|
auth := newTestYggdrasilAuth(t, api, "SkinUser")
|
||||||
@@ -703,7 +554,7 @@ func TestYggdrasilLoginFailure(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel)
|
server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -717,7 +568,7 @@ func TestYggdrasilLoginFailure(t *testing.T) {
|
|||||||
}
|
}
|
||||||
defer rawClient.Close()
|
defer rawClient.Close()
|
||||||
|
|
||||||
client, err := newClientConn(rawClient, latestProtocolVersion, nil, password, publicKey, "localhost", nil, newTestYggdrasilAuth(t, api, ""), DefaultDataChannel, DefaultPaddingChannel)
|
client, err := newClientConn(rawClient, nil, password, publicKey, "localhost", nil, newTestYggdrasilAuth(t, api, ""))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -28,11 +28,7 @@ func (s *Proxy) Proxy(w http.ResponseWriter, r *ProxyRequest) (*Conn, error) {
|
|||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
|
|
||||||
if ok {
|
if ok {
|
||||||
str, err := streamer.HTTPStream()
|
return newProxiedConn(streamer.HTTPStream()), nil
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
return newProxiedConn(str), nil
|
|
||||||
}
|
}
|
||||||
controller := http.NewResponseController(w)
|
controller := http.NewResponseController(w)
|
||||||
if err := controller.Flush(); err != nil {
|
if err := controller.Flush(); err != nil {
|
||||||
|
|||||||
@@ -231,11 +231,7 @@ func TestDialWarpHTTP3(t *testing.T) {
|
|||||||
}
|
}
|
||||||
w.WriteHeader(http.StatusOK)
|
w.WriteHeader(http.StatusOK)
|
||||||
w.(http.Flusher).Flush()
|
w.(http.Flusher).Flush()
|
||||||
str, err := w.(http3.HTTPStreamer).HTTPStream()
|
str := w.(http3.HTTPStreamer).HTTPStream()
|
||||||
if err != nil {
|
|
||||||
t.Error(err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
go func() { capsules <- readCapsuleTypes(str, nil) }()
|
go func() { capsules <- readCapsuleTypes(str, nil) }()
|
||||||
b, err := str.ReceiveDatagram(r.Context())
|
b, err := str.ReceiveDatagram(r.Context())
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|||||||
@@ -26,7 +26,6 @@ import (
|
|||||||
"github.com/xtls/xray-core/common/net"
|
"github.com/xtls/xray-core/common/net"
|
||||||
http_proto "github.com/xtls/xray-core/common/protocol/http"
|
http_proto "github.com/xtls/xray-core/common/protocol/http"
|
||||||
"github.com/xtls/xray-core/common/signal/done"
|
"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"
|
||||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion"
|
"github.com/xtls/xray-core/transport/internet/hysteria/congestion"
|
||||||
"github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr"
|
"github.com/xtls/xray-core/transport/internet/hysteria/congestion/bbr"
|
||||||
@@ -79,9 +78,10 @@ func (h *requestHandler) upsertSession(sessionId string) *httpSession {
|
|||||||
h.sessions.Store(sessionId, s)
|
h.sessions.Store(sessionId, s)
|
||||||
|
|
||||||
shouldReap := done.New()
|
shouldReap := done.New()
|
||||||
time.AfterFunc(30*time.Second, func() {
|
go func() {
|
||||||
|
time.Sleep(30 * time.Second)
|
||||||
shouldReap.Close()
|
shouldReap.Close()
|
||||||
})
|
}()
|
||||||
go func() {
|
go func() {
|
||||||
select {
|
select {
|
||||||
case <-shouldReap.Wait():
|
case <-shouldReap.Wait():
|
||||||
@@ -222,15 +222,15 @@ func (h *requestHandler) ServeHTTP(writer http.ResponseWriter, request *http.Req
|
|||||||
scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs()
|
scStreamUpServerSecs := h.config.GetNormalizedScStreamUpServerSecs()
|
||||||
hasLegacyRefererCompatMarker := request.Header.Get("Referer") != ""
|
hasLegacyRefererCompatMarker := request.Header.Get("Referer") != ""
|
||||||
if (hasLegacyRefererCompatMarker || obfsPaddingAccepted) && scStreamUpServerSecs.To > 0 {
|
if (hasLegacyRefererCompatMarker || obfsPaddingAccepted) && scStreamUpServerSecs.To > 0 {
|
||||||
writePadding := &task.Periodic{
|
go func() {
|
||||||
Execute: func() error {
|
for {
|
||||||
_, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand())))
|
_, err := httpSC.Write(bytes.Repeat([]byte{'X'}, int(h.config.GetNormalizedXPaddingBytes().rand())))
|
||||||
return err
|
if err != nil {
|
||||||
},
|
break
|
||||||
Interval: time.Duration(scStreamUpServerSecs.rand()) * time.Second,
|
}
|
||||||
}
|
time.Sleep(time.Duration(scStreamUpServerSecs.rand()) * time.Second)
|
||||||
defer writePadding.Close()
|
}
|
||||||
writePadding.Start()
|
}()
|
||||||
}
|
}
|
||||||
select {
|
select {
|
||||||
case <-request.Context().Done():
|
case <-request.Context().Done():
|
||||||
|
|||||||
@@ -6,11 +6,9 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"github.com/gorilla/websocket"
|
||||||
"github.com/xtls/xray-core/common"
|
|
||||||
"github.com/xtls/xray-core/common/buf"
|
"github.com/xtls/xray-core/common/buf"
|
||||||
"github.com/xtls/xray-core/common/errors"
|
"github.com/xtls/xray-core/common/errors"
|
||||||
"github.com/xtls/xray-core/common/serial"
|
"github.com/xtls/xray-core/common/serial"
|
||||||
"github.com/xtls/xray-core/common/task"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
var _ buf.Writer = (*connection)(nil)
|
var _ buf.Writer = (*connection)(nil)
|
||||||
@@ -22,27 +20,25 @@ type connection struct {
|
|||||||
conn *websocket.Conn
|
conn *websocket.Conn
|
||||||
reader io.Reader
|
reader io.Reader
|
||||||
remoteAddr net.Addr
|
remoteAddr net.Addr
|
||||||
keepalive *task.Periodic
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewConnection(conn *websocket.Conn, remoteAddr net.Addr, extraReader io.Reader, heartbeatPeriod uint32) *connection {
|
func NewConnection(conn *websocket.Conn, remoteAddr net.Addr, extraReader io.Reader, heartbeatPeriod uint32) *connection {
|
||||||
wrappedConn := &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{
|
||||||
conn: conn,
|
conn: conn,
|
||||||
remoteAddr: remoteAddr,
|
remoteAddr: remoteAddr,
|
||||||
reader: extraReader,
|
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()
|
// Read implements net.Conn.Read()
|
||||||
@@ -97,7 +93,6 @@ func (c *connection) WriteMultiBuffer(mb buf.MultiBuffer) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *connection) Close() error {
|
func (c *connection) Close() error {
|
||||||
common.CloseIfExists(c.keepalive)
|
|
||||||
var errs []interface{}
|
var errs []interface{}
|
||||||
if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
|
if err := c.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second*5)); err != nil {
|
||||||
errs = append(errs, err)
|
errs = append(errs, err)
|
||||||
|
|||||||
Reference in New Issue
Block a user