yangdujun
2026-11-18 08:27:34 +00:00
committed by GitHub
parent 82b5b76bc5
commit a32023be5f
13 changed files with 628 additions and 150 deletions
+17 -2
View File
@@ -936,12 +936,20 @@ type XMC struct {
Profiles []XMCProfile `json:"profiles"`
Password string `json:"password"`
Paddings []XMCPaddingTurn `json:"paddings,omitempty"`
// A configured list is the complete padding schedule and replaces the
// built-in preset entirely, including the preset's Play-state join tail.
// NoPadding disables padding. An explicit empty "paddings" array means the
// same; an absent one keeps the built-in preset.
NoPadding bool `json:"noPadding,omitempty"`
}
type XMCPaddingTurn struct {
Length string `json:"length"`
Direction string `json:"direction"`
// Delay is an optional millisecond value or inclusive min-max range.
// Delay is an optional millisecond value or inclusive min-max range: the
// pause that leads into this turn, written on the turn that follows the gap
// it reproduces. The sending side samples the range, the peer spends its
// minimum, and nothing pauses after the last turn.
Delay string `json:"delay,omitempty"`
}
@@ -988,7 +996,14 @@ func (c *XMC) Build() (proto.Message, error) {
if len(c.Password) > xmc.MaxLegacyPasswordLength {
return nil, fmt.Errorf("minecraft password is longer than %d bytes", xmc.MaxLegacyPasswordLength)
}
config := &xmc.Config{Password: c.Password, Hostname: c.Hostname}
// An explicit empty array is different from an absent field: json leaves
// Paddings nil when it is absent, so the user can turn padding off without
// a second switch.
noPadding := c.NoPadding || (c.Paddings != nil && len(c.Paddings) == 0)
if noPadding && len(c.Paddings) > 0 {
return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive")
}
config := &xmc.Config{Password: c.Password, Hostname: c.Hostname, NoPadding: noPadding}
for i, turn := range c.Paddings {
minimum, maximum, err := ParseRangeString(turn.Length)
if err != nil {
@@ -112,3 +112,42 @@ func TestXMCBuildRejectsLongPassword(t *testing.T) {
t.Fatalf("expected a password length error, got %v", err)
}
}
func TestXMCBuildDisablesPadding(t *testing.T) {
profile := XMCProfile{
Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff",
TexturesValue: "textures-value", TexturesSignature: "textures-signature",
}
for name, settings := range map[string]string{
"explicit_empty_array": `{"paddings": []}`,
"no_padding_switch": `{"noPadding": true}`,
} {
t.Run(name, func(t *testing.T) {
var config XMC
if err := json.Unmarshal([]byte(settings), &config); err != nil {
t.Fatal(err)
}
config.Password = "test-password"
config.Profiles = []XMCProfile{profile}
built, err := config.Build()
if err != nil {
t.Fatalf("build XMC config: %v", err)
}
builtConfig := built.(*xmc.Config)
if !builtConfig.NoPadding || len(builtConfig.Paddings) != 0 {
t.Fatalf("padding was not disabled: %+v", builtConfig)
}
})
}
var config XMC
if err := json.Unmarshal([]byte(`{"noPadding": true, "paddings": [{"length": "3", "direction": "c2s"}]}`), &config); err != nil {
t.Fatal(err)
}
config.Password = "test-password"
config.Profiles = []XMCProfile{profile}
if _, err := config.Build(); err == nil || !strings.Contains(err.Error(), "exclusive") {
t.Fatalf("expected an exclusive padding error, got %v", err)
}
}
+16 -8
View File
@@ -32,6 +32,9 @@ type clientConn struct {
paddingSchedule []paddingTurn
packet *packetStream
deadlines *connectionDeadlines
done chan struct{}
closeOnce sync.Once
}
type clientState int
@@ -41,7 +44,7 @@ var (
clientStateProxy clientState = 2
)
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, padding []*Padding) (*clientConn, error) {
func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn) (*clientConn, error) {
if len(rsaPublicKey) == 0 {
return nil, fmt.Errorf("empty rsa public key")
}
@@ -51,10 +54,6 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
if len(password) > MaxLegacyPasswordLength {
return nil, fmt.Errorf("password is longer than %d bytes", MaxLegacyPasswordLength)
}
paddingSchedule, err := newPaddingSchedule(padding, true)
if err != nil {
return nil, fmt.Errorf("select padding profile: %w", err)
}
return &clientConn{
reader: bufio.NewReader(c),
writer: c,
@@ -67,9 +66,15 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl
hostname: hostname,
paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c),
done: make(chan struct{}),
}, nil
}
// paddingPause applies one padding pause, stopping early on Close.
func (c *clientConn) paddingPause(d time.Duration) error {
return pausePadding(c.done, d)
}
func (c *clientConn) handshake() error {
c.handshakeLock.Lock()
defer c.handshakeLock.Unlock()
@@ -199,7 +204,9 @@ func (c *clientConn) handshake() error {
return fmt.Errorf("read login finished: %w", err)
}
// Set Compression is not compressed itself and must be handled before the
// packet that follows it, which already uses the compressed framing.
// packet that follows it, which already uses the compressed framing. The
// threshold only decides whether the framing applies: this writer never
// compresses, so a server-side threshold does not shrink padding turns.
if pkt.packetID == 0x03 {
var threshold Varint
if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil {
@@ -207,7 +214,7 @@ func (c *clientConn) handshake() error {
}
if threshold >= 0 {
c.reader = newCompressionReader(c.reader)
c.writer = newCompressionWriter(c.writer, int32(threshold))
c.writer = newCompressionWriter(c.writer)
}
pkt, err = readPacket(c.reader)
if err != nil {
@@ -237,7 +244,7 @@ func (c *clientConn) handshake() error {
return fmt.Errorf("write login acknowledged: %w", err)
}
c.reader = newPaddingReader(c.reader, true)
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule); err != nil {
if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil {
_ = c.Close() // Unblock the startup reader if writing failed.
return fmt.Errorf("run startup padding: %w", err)
}
@@ -281,6 +288,7 @@ func (c *clientConn) Close() error {
c.closed = true
packet := c.packet
c.lifecycleMu.Unlock()
c.closeOnce.Do(func() { close(c.done) })
if packet != nil {
packet.Stop()
}
+20 -34
View File
@@ -1,4 +1,6 @@
// Minecraft compression framing, negotiated by the login Set Compression packet.
// The reader decodes whatever the peer sends, including deflated bodies; the
// writer always sends the uncompressed variant.
package xmc
import (
@@ -99,14 +101,21 @@ func (c *compressionReader) readFrame() error {
// compressionWriter converts a plain frame (VarInt body length, body) into the
// post-Set Compression framing. Frames are buffered until complete, because a
// caller may split one frame across several Write calls.
//
// It never compresses, whatever the negotiated threshold is. What XMC writes is
// padding and proxied bytes: the padding exists for its size on the wire, so
// deflating it would shrink a padded turn from tens of kilobytes to a hundred
// bytes and erase the shape it is there for, and proxied bytes are already
// encrypted or compressed by whoever produced them. Vanilla accepts an
// uncompressed body of any size when Data Length is zero, so the framing alone
// is enough to stay inside the protocol.
type compressionWriter struct {
w io.Writer
threshold int32
pending []byte
w io.Writer
pending []byte
}
func newCompressionWriter(w io.Writer, threshold int32) io.Writer {
return &compressionWriter{w: w, threshold: threshold}
func newCompressionWriter(w io.Writer) io.Writer {
return &compressionWriter{w: w}
}
func (c *compressionWriter) Write(p []byte) (int, error) {
@@ -156,36 +165,13 @@ func (c *compressionWriter) nextFrame() ([]byte, bool, error) {
}
func (c *compressionWriter) writeFrame(body []byte) error {
if len(body) >= int(c.threshold) {
var compressed bytes.Buffer
zw := zlib.NewWriter(&compressed)
if _, err := zw.Write(body); err != nil {
_ = zw.Close()
return fmt.Errorf("compress packet: %w", err)
}
if err := zw.Close(); err != nil {
return fmt.Errorf("close compressor: %w", err)
}
var frame bytes.Buffer
packetLength := varintSize(Varint(len(body))) + compressed.Len()
frame.Grow(varintSize(Varint(packetLength)) + packetLength)
packetLengthVarint := Varint(packetLength)
if err := packetLengthVarint.writeTo(&frame); err != nil {
return err
}
bodyLength := Varint(len(body))
if err := bodyLength.writeTo(&frame); err != nil {
return err
}
frame.Write(compressed.Bytes())
return writeFull(c.w, frame.Bytes())
}
// Packet Length covers the Data Length varint and the body; a zero Data
// Length is the uncompressed variant.
packetLength := 1 + len(body)
var frame bytes.Buffer
frame.Grow(varintSize(Varint(1+len(body))) + 1 + len(body))
frameLength := Varint(1 + len(body))
if err := frameLength.writeTo(&frame); err != nil {
frame.Grow(varintSize(Varint(packetLength)) + packetLength)
packetLengthVarint := Varint(packetLength)
if err := packetLengthVarint.writeTo(&frame); err != nil {
return err
}
frame.WriteByte(0)
@@ -2,6 +2,7 @@ package xmc
import (
"bytes"
"compress/zlib"
"crypto/rand"
"errors"
"io"
@@ -49,39 +50,39 @@ func randomBody(t *testing.T, size int) []byte {
return body
}
func TestCompressionWriterThreshold(t *testing.T) {
for _, threshold := range []int32{0, 1, 256, 65536} {
for _, size := range []int{1, 10, 255, 256, 257, 65535, 65536} {
body := bytes.Repeat([]byte{0}, size)
// TestCompressionWriterNeverCompresses pins the write policy: whatever the
// negotiated threshold is, XMC sends the uncompressed framing so that a padding
// turn keeps its wire size. A padded turn of zeros would otherwise deflate from
// tens of kilobytes to a hundred bytes and the shape would be gone.
func TestCompressionWriterNeverCompresses(t *testing.T) {
for _, size := range []int{1, 10, 255, 256, 257, 32768, 65535, 65536} {
for _, body := range [][]byte{bytes.Repeat([]byte{0}, size), randomBody(t, size)} {
var wire bytes.Buffer
w := newCompressionWriter(&wire, threshold)
w := newCompressionWriter(&wire)
if _, err := w.Write(plainFrame(body)); err != nil {
t.Fatalf("threshold %d size %d: write: %v", threshold, size, err)
t.Fatalf("size %d: write: %v", size, err)
}
frame := readWireFrame(t, bytes.NewReader(wire.Bytes()))
wantCompressed := int32(size) >= threshold
if wantCompressed && frame.dataLength != size {
t.Fatalf("threshold %d size %d: want compressed data length %d, got %d", threshold, size, size, frame.dataLength)
if frame.dataLength != 0 {
t.Fatalf("size %d: writer compressed the body (data length %d)", size, frame.dataLength)
}
if !wantCompressed {
if frame.dataLength != 0 {
t.Fatalf("threshold %d size %d: want uncompressed frame, got data length %d", threshold, size, frame.dataLength)
}
if !bytes.Equal(frame.payload, body) {
t.Fatalf("threshold %d size %d: uncompressed payload mismatch", threshold, size)
}
if frame.packetLength != 1+size {
t.Fatalf("threshold %d size %d: packet length %d", threshold, size, frame.packetLength)
}
if !bytes.Equal(frame.payload, body) {
t.Fatalf("size %d: payload mismatch", size)
}
if frame.packetLength != 1+size {
t.Fatalf("size %d: packet length %d, want %d", size, frame.packetLength, 1+size)
}
if wire.Len() != varintSize(Varint(1+size))+1+size {
t.Fatalf("size %d: frame is %d bytes on the wire, want %d", size, wire.Len(), varintSize(Varint(1+size))+1+size)
}
decoded, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("threshold %d size %d: decode: %v", threshold, size, err)
t.Fatalf("size %d: decode: %v", size, err)
}
if !bytes.Equal(decoded, body) {
t.Fatalf("threshold %d size %d: round trip mismatch", threshold, size)
t.Fatalf("size %d: round trip mismatch", size)
}
}
}
@@ -96,38 +97,36 @@ func TestCompressionRoundTripChunked(t *testing.T) {
bytes.Repeat([]byte("xmc"), 8*1024),
}
for _, threshold := range []int32{0, 256, 65536} {
var wire bytes.Buffer
w := newCompressionWriter(&wire, threshold)
// One Write per frame, split into awkward chunk sizes.
for _, body := range cases {
frame := plainFrame(body)
for len(frame) > 0 {
n := 7
if n > len(frame) {
n = len(frame)
}
if _, err := w.Write(frame[:n]); err != nil {
t.Fatalf("threshold %d: chunked write: %v", threshold, err)
}
frame = frame[n:]
var wire bytes.Buffer
w := newCompressionWriter(&wire)
// One Write per frame, split into awkward chunk sizes.
for _, body := range cases {
frame := plainFrame(body)
for len(frame) > 0 {
n := 7
if n > len(frame) {
n = len(frame)
}
if _, err := w.Write(frame[:n]); err != nil {
t.Fatalf("chunked write: %v", err)
}
frame = frame[n:]
}
}
r := newCompressionReader(bytes.NewReader(wire.Bytes()))
for i, want := range cases {
got, _, err := readFrame(r, maxUncompressedFrameBody)
if err != nil {
t.Fatalf("threshold %d frame %d: decode: %v", threshold, i, err)
}
if !bytes.Equal(got, want) {
t.Fatalf("threshold %d frame %d: mismatch (%d vs %d bytes)", threshold, i, len(got), len(want))
}
r := newCompressionReader(bytes.NewReader(wire.Bytes()))
for i, want := range cases {
got, _, err := readFrame(r, maxUncompressedFrameBody)
if err != nil {
t.Fatalf("frame %d: decode: %v", i, err)
}
if _, _, err := readFrame(r, maxUncompressedFrameBody); !errors.Is(err, io.EOF) {
t.Fatalf("threshold %d: expected EOF after the last frame, got %v", threshold, err)
if !bytes.Equal(got, want) {
t.Fatalf("frame %d: mismatch (%d vs %d bytes)", i, len(got), len(want))
}
}
if _, _, err := readFrame(r, maxUncompressedFrameBody); !errors.Is(err, io.EOF) {
t.Fatalf("expected EOF after the last frame, got %v", err)
}
}
func TestCompressionMultipleFramesOneWrite(t *testing.T) {
@@ -138,7 +137,7 @@ func TestCompressionMultipleFramesOneWrite(t *testing.T) {
}
var wire bytes.Buffer
w := newCompressionWriter(&wire, 256)
w := newCompressionWriter(&wire)
if _, err := w.Write(plain); err != nil {
t.Fatalf("write: %v", err)
}
@@ -176,6 +175,40 @@ func TestCompressionReaderUncompressedOverThreshold(t *testing.T) {
}
}
// The writer stopped compressing, but a real server still does, so the reader
// must keep decoding deflated bodies.
func TestCompressionReaderDecodesCompressedBody(t *testing.T) {
body := append(bytes.Repeat([]byte("xmc"), 4096), 0, 1, 2, 3)
var compressed bytes.Buffer
zw := zlib.NewWriter(&compressed)
if _, err := zw.Write(body); err != nil {
t.Fatal(err)
}
if err := zw.Close(); err != nil {
t.Fatal(err)
}
var wire bytes.Buffer
packetLength := Varint(varintSize(Varint(len(body))) + compressed.Len())
if err := packetLength.writeTo(&wire); err != nil {
t.Fatal(err)
}
dataLength := Varint(len(body))
if err := dataLength.writeTo(&wire); err != nil {
t.Fatal(err)
}
wire.Write(compressed.Bytes())
got, _, err := readFrame(newCompressionReader(bytes.NewReader(wire.Bytes())), maxUncompressedFrameBody)
if err != nil {
t.Fatalf("decode: %v", err)
}
if !bytes.Equal(got, body) {
t.Fatal("payload mismatch")
}
}
func TestCompressionReaderErrors(t *testing.T) {
// Compressed packet with a bogus body.
var badZlib bytes.Buffer
@@ -213,7 +246,7 @@ func TestCompressionReaderErrors(t *testing.T) {
func TestCompressionWriterInvalidFrameLength(t *testing.T) {
var wire bytes.Buffer
w := newCompressionWriter(&wire, 256)
w := newCompressionWriter(&wire)
if _, err := w.Write([]byte{0xff, 0xff, 0xff, 0xff, 0xff}); err == nil {
t.Fatal("expected an error for an invalid frame length prefix")
}
+56 -14
View File
@@ -23,7 +23,11 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname, c.Paddings)
paddingSchedule, err := c.paddingSchedule(true)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname, paddingSchedule)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
@@ -36,7 +40,11 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, c.Paddings)
paddingSchedule, err := c.paddingSchedule(false)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule)
if err != nil {
return nil, fmt.Errorf("minecraft finalmask: %w", err)
}
@@ -44,16 +52,53 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) {
return cc, nil
}
// ValidatePadding checks custom startup turns without selecting a built-in preset.
// ValidatePadding checks the configured startup turns (including their bounds)
// without selecting a built-in preset.
func (c *Config) ValidatePadding() error {
if c.NoPadding {
if len(c.Paddings) != 0 {
return fmt.Errorf("padding is disabled and configured at the same time")
}
return nil
}
_, err := paddingScheduleFromConfig(c.Paddings)
return err
}
// paddingSchedule selects the padding turns for one connection. An explicit
// empty configuration disables padding; an absent one keeps the built-in
// preset.
//
// A configured list is the complete schedule, not a replacement for its startup
// part: the built-in preset also carries a Play-state join tail, and that tail
// runs only with the preset. A user who captured their own login decides the
// whole shape, including whether it has a tail.
func (c *Config) paddingSchedule(isClient bool) ([]paddingTurn, error) {
if c.NoPadding {
if len(c.Paddings) != 0 {
return nil, fmt.Errorf("padding is disabled and configured at the same time")
}
return nil, nil
}
if len(c.Paddings) > 0 {
return paddingScheduleFromConfig(c.Paddings)
}
if isClient {
return newClientPaddingSchedule2612()
}
return newServerPaddingSchedule2612()
}
// paddingScheduleFromConfig builds the complete schedule from a configured list.
// The list replaces the preset entirely, including its Play-state join tail.
func paddingScheduleFromConfig(paddings []*Padding) ([]paddingTurn, error) {
if len(paddings) == 0 {
return nil, nil
}
if len(paddings) > maxPaddingTurns {
return nil, fmt.Errorf("too many padding turns: %d (at most %d)", len(paddings), maxPaddingTurns)
}
var totalLength, totalDelayMilliseconds int64
schedule := make([]paddingTurn, len(paddings))
for i, turn := range paddings {
if turn == nil || turn.LengthMin < 1 || turn.LengthMax < turn.LengthMin || turn.LengthMax > maxPaddingTurnLength {
@@ -65,6 +110,14 @@ func paddingScheduleFromConfig(paddings []*Padding) ([]paddingTurn, error) {
if turn.DelayMax > maxPaddingDelayMilliseconds {
return nil, fmt.Errorf("padding delay range %d-%d at turn %d is too large", turn.DelayMin, turn.DelayMax, i)
}
totalLength += turn.LengthMax
if totalLength > maxPaddingTotalLength {
return nil, fmt.Errorf("padding turns are longer than %d bytes in total", maxPaddingTotalLength)
}
totalDelayMilliseconds += turn.DelayMax
if totalDelayMilliseconds > int64(maxPaddingScheduleDelay/time.Millisecond) {
return nil, fmt.Errorf("padding pauses are longer than %s in total", maxPaddingScheduleDelay)
}
var direction paddingDirection
switch turn.Direction {
case 1:
@@ -90,14 +143,3 @@ func paddingScheduleFromConfig(paddings []*Padding) ([]paddingTurn, error) {
}
return schedule, nil
}
func newPaddingSchedule(paddings []*Padding, isClient bool) ([]paddingTurn, error) {
schedule, err := paddingScheduleFromConfig(paddings)
if err != nil || schedule != nil {
return schedule, err
}
if isClient {
return newClientPaddingSchedule2612()
}
return newServerPaddingSchedule2612()
}
+26 -7
View File
@@ -99,8 +99,13 @@ type Config struct {
RsaPublicKey []byte `protobuf:"bytes,9,opt,name=rsa_public_key,json=rsaPublicKey,proto3" json:"rsa_public_key,omitempty"`
Hostname string `protobuf:"bytes,10,opt,name=hostname,proto3" json:"hostname,omitempty"`
Profiles []*Profile `protobuf:"bytes,11,rep,name=profiles,proto3" json:"profiles,omitempty"`
// Startup padding turns. Empty uses the built-in preset.
Paddings []*Padding `protobuf:"bytes,12,rep,name=paddings,proto3" json:"paddings,omitempty"`
// Padding turns. Empty uses the built-in preset, unless no_padding is set.
// A configured list is the complete schedule and replaces the preset
// entirely: the preset's Play-state join tail runs only with the preset.
Paddings []*Padding `protobuf:"bytes,12,rep,name=paddings,proto3" json:"paddings,omitempty"`
// Disables startup padding. The configuration sets this for an explicit
// empty "paddings" array, which an unset repeated field cannot express.
NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
@@ -177,15 +182,27 @@ func (x *Config) GetPaddings() []*Padding {
return nil
}
func (x *Config) GetNoPadding() bool {
if x != nil {
return x.NoPadding
}
return false
}
type Padding struct {
state protoimpl.MessageState `protogen:"open.v1"`
LengthMin int64 `protobuf:"varint,1,opt,name=length_min,json=lengthMin,proto3" json:"length_min,omitempty"`
LengthMax int64 `protobuf:"varint,2,opt,name=length_max,json=lengthMax,proto3" json:"length_max,omitempty"`
// 1 = client to server, 2 = server to client
Direction int32 `protobuf:"varint,3,opt,name=direction,proto3" json:"direction,omitempty"`
// Millisecond pause after this turn, including the last one. The sender
// waits for a uniformly selected value in [delay_min, delay_max]; the
// receiver waits at least delay_min. Zero means no delay.
// Millisecond pause that leads into this turn: it sits between the previous
// padding turn (or Login Acknowledged, for the first turn) and this turn's
// bytes, so a captured gap is written on the turn that follows it. The side
// that sends the turn waits for a uniformly selected value in
// [delay_min, delay_max]; the peer spends exactly delay_min at the same
// place, so only the sending side jitters: use delay_min == delay_max to
// reproduce a captured gap. Nothing pauses after the last turn. Zero means
// no pause.
DelayMin int64 `protobuf:"varint,4,opt,name=delay_min,json=delayMin,proto3" json:"delay_min,omitempty"`
DelayMax int64 `protobuf:"varint,5,opt,name=delay_max,json=delayMax,proto3" json:"delay_max,omitempty"`
unknownFields protoimpl.UnknownFields
@@ -266,7 +283,7 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\busername\x18\x01 \x01(\tR\busername\x12\x12\n" +
"\x04uuid\x18\x02 \x01(\fR\x04uuid\x12%\n" +
"\x0etextures_value\x18\x03 \x01(\tR\rtexturesValue\x12-\n" +
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xac\x02\n" +
"\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xcb\x02\n" +
"\x06Config\x12\x1a\n" +
"\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" +
"\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" +
@@ -274,7 +291,9 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" +
"\bhostname\x18\n" +
" \x01(\tR\bhostname\x12J\n" +
"\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofiles\x12J\n" +
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddingsJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
"\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddings\x12\x1d\n" +
"\n" +
"no_padding\x18\x0e \x01(\bR\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\n" +
"\aPadding\x12\x1d\n" +
"\n" +
"length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" +
+14 -4
View File
@@ -23,8 +23,13 @@ message Config {
bytes rsa_public_key = 9;
string hostname = 10;
repeated Profile profiles = 11;
// Startup padding turns. Empty uses the built-in preset.
// Padding turns. Empty uses the built-in preset, unless no_padding is set.
// A configured list is the complete schedule and replaces the preset
// entirely: the preset's Play-state join tail runs only with the preset.
repeated Padding paddings = 12;
// Disables startup padding. The configuration sets this for an explicit
// empty "paddings" array, which an unset repeated field cannot express.
bool no_padding = 14;
}
message Padding {
@@ -32,9 +37,14 @@ message Padding {
int64 length_max = 2;
// 1 = client to server, 2 = server to client
int32 direction = 3;
// Millisecond pause after this turn, including the last one. The sender
// waits for a uniformly selected value in [delay_min, delay_max]; the
// receiver waits at least delay_min. Zero means no delay.
// Millisecond pause that leads into this turn: it sits between the previous
// padding turn (or Login Acknowledged, for the first turn) and this turn's
// bytes, so a captured gap is written on the turn that follows it. The side
// that sends the turn waits for a uniformly selected value in
// [delay_min, delay_max]; the peer spends exactly delay_min at the same
// place, so only the sending side jitters: use delay_min == delay_max to
// reproduce a captured gap. Nothing pauses after the last turn. Zero means
// no pause.
int64 delay_min = 4;
int64 delay_max = 5;
}
@@ -1,9 +1,11 @@
package xmc
import (
"errors"
"net"
"strings"
"testing"
"time"
)
func TestClientRejectsLongLegacyPassword(t *testing.T) {
@@ -21,3 +23,126 @@ func TestClientRejectsLongLegacyPassword(t *testing.T) {
t.Fatal("expected the long password to be rejected")
}
}
func TestPaddingScheduleCaps(t *testing.T) {
turn := func(length, delay int64) *Padding {
return &Padding{LengthMin: length, LengthMax: length, Direction: 1, DelayMin: delay, DelayMax: delay}
}
t.Run("too many turns", func(t *testing.T) {
paddings := make([]*Padding, maxPaddingTurns+1)
for i := range paddings {
paddings[i] = turn(3, 0)
}
if _, err := paddingScheduleFromConfig(paddings); err == nil {
t.Fatal("expected a turn count error")
}
})
t.Run("too many bytes", func(t *testing.T) {
paddings := make([]*Padding, maxPaddingTotalLength/maxPaddingTurnLength+1)
for i := range paddings {
paddings[i] = turn(maxPaddingTurnLength, 0)
}
if _, err := paddingScheduleFromConfig(paddings); err == nil {
t.Fatal("expected a total length error")
}
})
t.Run("too much delay", func(t *testing.T) {
tooLong := int64(maxPaddingScheduleDelay/time.Millisecond) + 1
if _, err := paddingScheduleFromConfig([]*Padding{turn(3, tooLong)}); err == nil {
t.Fatal("expected a total delay error")
}
if _, err := paddingScheduleFromConfig([]*Padding{turn(3, int64(maxPaddingScheduleDelay/time.Millisecond))}); err != nil {
t.Fatalf("delay at the limit was rejected: %v", err)
}
})
}
func TestPaddingDisabled(t *testing.T) {
config := &Config{NoPadding: true}
if err := config.ValidatePadding(); err != nil {
t.Fatalf("disabled padding failed validation: %v", err)
}
schedule, err := config.paddingSchedule(true)
if err != nil {
t.Fatal(err)
}
if schedule != nil {
t.Fatalf("disabled padding returned %d turns", len(schedule))
}
config.Paddings = []*Padding{{LengthMin: 3, LengthMax: 3, Direction: 1}}
if err := config.ValidatePadding(); err == nil {
t.Fatal("expected a conflict between disabled and configured padding")
}
if _, err := config.paddingSchedule(false); err == nil {
t.Fatal("expected a conflict between disabled and configured padding")
}
preset := &Config{}
if schedule, err := preset.paddingSchedule(true); err != nil || len(schedule) == 0 {
t.Fatalf("client preset = %d turns, err %v", len(schedule), err)
}
if schedule, err := preset.paddingSchedule(false); err != nil || len(schedule) == 0 {
t.Fatalf("server preset = %d turns, err %v", len(schedule), err)
}
}
// TestConfiguredPaddingsReplaceTheWholePreset pins the documented policy: a
// configured list is the complete schedule, so the preset's Play-state join tail
// does not run behind it on either end.
func TestConfiguredPaddingsReplaceTheWholePreset(t *testing.T) {
config := &Config{Paddings: []*Padding{
{LengthMin: 44, LengthMax: 44, Direction: 1},
{LengthMin: 64, LengthMax: 64, Direction: 2},
}}
for _, isClient := range []bool{true, false} {
schedule, err := config.paddingSchedule(isClient)
if err != nil {
t.Fatal(err)
}
if len(schedule) != len(config.Paddings) {
t.Fatalf("isClient=%v: schedule has %d turns, want the %d configured turns", isClient, len(schedule), len(config.Paddings))
}
for i, turn := range schedule {
want := paddingClientToServer
if config.Paddings[i].Direction == 2 {
want = paddingServerToClient
}
if turn.direction != want || turn.minLength != int(config.Paddings[i].LengthMin) {
t.Fatalf("isClient=%v: turn %d = %+v, want the configured %+v", isClient, i, turn, config.Paddings[i])
}
}
}
// The preset, in contrast, carries the join tail behind the startup turns.
preset, err := (&Config{}).paddingSchedule(true)
if err != nil {
t.Fatal(err)
}
if len(preset) <= len(startupPaddingSchedule2612) {
t.Fatalf("preset has %d turns, want the startup turns plus the join tail", len(preset))
}
}
func TestCloseCancelsPaddingPause(t *testing.T) {
client, server := net.Pipe()
defer server.Close()
conn, err := newClientConn(client, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil)
if err != nil {
t.Fatal(err)
}
if err := conn.Close(); err != nil {
t.Fatal(err)
}
started := time.Now()
if err := conn.paddingPause(time.Hour); !errors.Is(err, net.ErrClosed) {
t.Fatalf("expected net.ErrClosed, got %v", err)
}
if time.Since(started) > time.Second {
t.Fatal("closing the connection did not cancel the pause")
}
}
@@ -60,12 +60,16 @@ func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, lengt
{Direction: 1, LengthMin: length, LengthMax: length},
{Direction: 2, LengthMin: length, LengthMax: length},
}
client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", padding)
paddingSchedule, err := paddingScheduleFromConfig(padding)
if err != nil {
t.Fatal(err)
}
client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", paddingSchedule)
if err != nil {
t.Fatal(err)
}
defer client.Close()
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, padding)
server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule)
if err != nil {
t.Fatal(err)
}
+61 -21
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"io"
"math/big"
"net"
"time"
)
@@ -18,6 +19,16 @@ const (
maxPaddingChunkLength = 48 * 1024
maxPaddingTurnLength = 8 * 1024 * 1024
// A configured schedule is bounded so that one handshake cannot be told to
// send an arbitrary amount of padding: maxPaddingTurns limits the number of
// turns and maxPaddingTotalLength the worst-case sum of their lengths.
maxPaddingTurns = 256
maxPaddingTotalLength = 64 << 20
// maxPaddingScheduleDelay keeps the configured pauses inside the handshake
// deadline. A schedule that cannot finish before the deadline would fail
// every connection, so it is rejected when the configuration is built.
maxPaddingScheduleDelay = handshakeTimeout - 10*time.Second
// Frame padding carries the startup padding in ordinary Minecraft custom
// payload packets so that a vanilla server can parse the whole connection
// without taking the pipeline over. The channel is deliberately different
@@ -43,10 +54,12 @@ type paddingDelayRange struct {
}
type paddingTurn struct {
direction paddingDirection
minLength int
maxLength int
delay paddingDelayRange // pause after this turn, including the last one
direction paddingDirection
minLength int
maxLength int
// delay leads into this turn: the side that sends it samples the range, the
// peer spends its minimum, and no pause follows the last turn.
delay paddingDelayRange
variants []paddingVariant
startDelay paddingDelayRange
chunkDelay paddingDelayRange
@@ -57,11 +70,37 @@ type paddingTurn struct {
sendVariants []int
}
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn) error {
return runPaddingScheduleWithSleep(writer, isClient, firstTurnPrefixLength, schedule, time.Sleep)
// pausePadding waits for one padding pause. It returns as soon as the
// connection is closed so that a handshake cannot keep sleeping after its
// connection is gone.
func pausePadding(done <-chan struct{}, d time.Duration) error {
if d <= 0 {
return nil
}
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-done:
return net.ErrClosed
}
}
func runPaddingScheduleWithSleep(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration)) error {
// runPaddingSchedule sends the local turns of the schedule and applies the
// configured pauses. A turn's pause leads into the turn, so the bytes of a turn
// always follow the pause that was configured next to it, and nothing pauses
// after the last turn: the proxy stream follows it directly. An empty schedule
// means padding is disabled and nothing is written or waited for.
//
// Nothing here checks when a peer's turn arrives: the turns are ordinary
// Minecraft packets that carry nothing to compare an early arrival against, and
// the startup reader drains them on its own while this schedule writes. A peer
// that stalls is bounded by maxPaddingScheduleDelay instead.
func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error) error {
if len(schedule) == 0 {
return nil
}
if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil {
return err
}
@@ -74,22 +113,23 @@ func runPaddingScheduleWithSleep(writer io.Writer, isClient bool, firstTurnPrefi
if isClient != (turn.direction == paddingClientToServer) {
// The startup reader drains peer padding independently so writes
// cannot fill both connection buffers. Both endpoints still apply
// the same minimum pause, including after the last turn.
if turn.delay.min > 0 {
sleep(turn.delay.min)
// cannot fill both connection buffers. The peer still spends the
// same pause at the same place in the schedule, which keeps both
// timelines in phase; it only knows the minimum.
if err := sleep(turn.delay.min); err != nil {
return err
}
continue
}
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil {
return fmt.Errorf("write padding turn %d: %w", i, err)
}
delay, err := randomPaddingDelay(turn.delay)
if err != nil {
return fmt.Errorf("select padding turn %d delay: %w", i, err)
}
if delay > 0 {
sleep(delay)
if err := sleep(delay); err != nil {
return err
}
if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil {
return fmt.Errorf("write padding turn %d: %w", i, err)
}
}
return nil
@@ -166,13 +206,13 @@ func paddingFramePacketID(isClient bool) int {
// writePaddingTurnFrames writes one padding turn as a sequence of valid
// Minecraft custom payload frames. Only the framing is native: payload bodies
// stay zero-filled, so the captured traffic shape is kept.
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration), packetID int) (int, error) {
func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int) (int, error) {
startDelay, err := randomPaddingDelay(turn.startDelay)
if err != nil {
return 0, fmt.Errorf("select padding start delay: %w", err)
}
if startDelay > 0 {
sleep(startDelay)
if err := sleep(startDelay); err != nil {
return 0, err
}
targetLength, chunks, delays, err := selectPaddingVariant(turn, prefixLength)
@@ -209,8 +249,8 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle
if delayErr != nil {
return written, fmt.Errorf("select padding chunk %d delay: %w", i, delayErr)
}
if delay > 0 {
sleep(delay)
if delayErr = sleep(delay); delayErr != nil {
return written, delayErr
}
}
frameLengths, planErr := paddingFramePlan(chunkLength)
@@ -2,6 +2,10 @@ package xmc
import (
"bytes"
"errors"
"io"
"net"
"strings"
"testing"
"time"
)
@@ -58,7 +62,7 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) {
}
for i, turn := range turns {
var buffer bytes.Buffer
written, err := writePaddingTurnFrames(&buffer, turn, 0, func(time.Duration) {}, configurationServerboundCustomPayload)
written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationServerboundCustomPayload)
if err != nil {
t.Fatalf("turn %d: %v", i, err)
}
@@ -103,7 +107,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) {
}
var out bytes.Buffer
if err := runPaddingSchedule(&out, true, 2, schedule); err != nil {
if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause); err != nil {
t.Fatal(err)
}
@@ -131,7 +135,154 @@ func TestRunPaddingScheduleRejectsInvalidSchedule(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingServerToClient, minLength: 10, maxLength: 10},
}
if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule); 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")
}
}
func noPaddingPause(time.Duration) error { return nil }
func TestRunPaddingScheduleWithoutTurns(t *testing.T) {
var out bytes.Buffer
if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause); err != nil {
t.Fatal(err)
}
if out.Len() != 0 {
t.Fatalf("disabled padding wrote %d bytes", out.Len())
}
}
func TestRunPaddingScheduleStopsWhenClosed(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44, delay: millisecondRange(1000, 1000)},
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
}
var out bytes.Buffer
pauses := 0
sleep := func(d time.Duration) error {
if d <= 0 {
return nil
}
pauses++
return net.ErrClosed
}
err := runPaddingSchedule(&out, true, 2, schedule, sleep)
if !errors.Is(err, net.ErrClosed) {
t.Fatalf("expected net.ErrClosed, got %v", err)
}
if pauses != 1 {
t.Fatalf("pauses = %d, want 1", pauses)
}
// The pause leads into turn 0, so the cancelled pause came before its bytes.
if out.Len() != 0 {
t.Fatalf("schedule kept writing after a cancelled pause: %d bytes", out.Len())
}
}
// recordingWriter records one event per write, so a test can see where the
// pauses fall relative to the padding bytes.
type recordingWriter struct {
events *[]string
}
func (w recordingWriter) Write(p []byte) (int, error) {
*w.events = append(*w.events, "write")
return len(p), nil
}
// TestPaddingDelayLeadsIntoTheTurn pins the placement of a configured pause:
// it belongs to the turn it precedes, the peer spends its minimum at the same
// place, and the last turn is not followed by one.
func TestPaddingDelayLeadsIntoTheTurn(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44, delay: millisecondRange(10, 10)},
{direction: paddingServerToClient, minLength: 20, maxLength: 20, delay: millisecondRange(20, 20)},
{direction: paddingClientToServer, minLength: 44, maxLength: 44, delay: millisecondRange(30, 30)},
}
run := func(isClient bool) []string {
var events []string
sleep := func(d time.Duration) error {
if d > 0 {
events = append(events, "pause "+d.String())
}
return nil
}
if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep); err != nil {
t.Fatal(err)
}
return events
}
// The client sends turns 0 and 2, so it pauses before each of them and
// spends the minimum of turn 1 while the server sends it.
client := strings.Join(run(true), ",")
wantClient := "pause 10ms,write,pause 20ms,pause 30ms,write"
if client != wantClient {
t.Fatalf("client events = %q, want %q", client, wantClient)
}
// The server sends turn 1, so the same pauses lead into its bytes. The last
// turn's pause still happens, but nothing follows the final write.
server := strings.Join(run(false), ",")
wantServer := "pause 10ms,pause 20ms,write,pause 30ms"
if server != wantServer {
t.Fatalf("server events = %q, want %q", server, wantServer)
}
}
// TestPaddingDelayRangeJittersOnlyTheSender pins which value each end waits:
// the side that sends the turn samples the range, the peer spends the minimum.
func TestPaddingDelayRangeJittersOnlyTheSender(t *testing.T) {
schedule := []paddingTurn{
{direction: paddingClientToServer, minLength: 44, maxLength: 44, delay: millisecondRange(20, 200)},
{direction: paddingClientToServer, minLength: 44, maxLength: 44},
}
run := func(isClient bool) []time.Duration {
var pauses []time.Duration
sleep := func(d time.Duration) error {
if d > 0 {
pauses = append(pauses, d)
}
return nil
}
if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep); err != nil {
t.Fatal(err)
}
return pauses
}
// The peer, which sends nothing here, spends exactly the minimum.
if got := run(false); len(got) != 1 || got[0] != 20*time.Millisecond {
t.Fatalf("peer pauses = %v, want exactly [20ms]", got)
}
seenLarge := false
for i := 0; i < 64; i++ {
pauses := run(true)
if len(pauses) != 1 {
t.Fatalf("sender pauses = %v, want exactly one pause", pauses)
}
if pauses[0] < 20*time.Millisecond || pauses[0] > 200*time.Millisecond {
t.Fatalf("sender pause %s is outside the configured range", pauses[0])
}
if pauses[0] >= 20*time.Millisecond && pauses[0] <= 200*time.Millisecond && pauses[0] != 20*time.Millisecond {
seenLarge = true
}
}
if !seenLarge {
t.Fatal("the sender never sampled a value above the minimum")
}
}
func TestPaddingPauseReturnsOnClose(t *testing.T) {
done := make(chan struct{})
close(done)
started := time.Now()
if err := pausePadding(done, time.Hour); !errors.Is(err, net.ErrClosed) {
t.Fatalf("expected net.ErrClosed, got %v", err)
}
if time.Since(started) > time.Second {
t.Fatal("pausePadding did not return on close")
}
}
+12 -6
View File
@@ -41,6 +41,9 @@ type serverConn struct {
paddingSchedule []paddingTurn
packet *packetStream
deadlines *connectionDeadlines
done chan struct{}
closeOnce sync.Once
}
func (c *serverConn) handshake() error {
@@ -246,7 +249,7 @@ func (c *serverConn) handshake() error {
return err
}
c.reader = newPaddingReader(c.reader, false)
if err = runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule); err != nil {
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)
}
@@ -304,12 +307,18 @@ func (c *serverConn) Close() error {
c.closed = true
packet := c.packet
c.lifecycleMu.Unlock()
c.closeOnce.Do(func() { close(c.done) })
if packet != nil {
packet.Stop()
}
return c.c.Close()
}
// paddingPause applies one padding pause, stopping early on Close.
func (c *serverConn) paddingPause(d time.Duration) error {
return pausePadding(c.done, d)
}
func (c *serverConn) LocalAddr() net.Addr {
return c.c.LocalAddr()
}
@@ -330,7 +339,7 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error {
return c.deadlines.setWriteDeadline(t)
}
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, padding []*Padding) (*serverConn, error) {
func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn) (*serverConn, error) {
if len(profiles) == 0 {
return nil, fmt.Errorf("empty profiles")
}
@@ -344,10 +353,6 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
if err != nil {
return nil, fmt.Errorf("parse rsa private key: %w", err)
}
paddingSchedule, err := newPaddingSchedule(padding, false)
if err != nil {
return nil, fmt.Errorf("select padding profile: %w", err)
}
s := &serverConn{
reader: bufio.NewReader(c),
@@ -360,6 +365,7 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri
rsaPublicKey: rsaPublicKey,
paddingSchedule: paddingSchedule,
deadlines: newConnectionDeadlines(c),
done: make(chan struct{}),
}
return s, nil