From 5d17b872edde3024a5b906d9cd6c7a3ad4973d81 Mon Sep 17 00:00:00 2001 From: Sparrow <248678851+spr334-a@users.noreply.github.com> Date: Sun, 15 Nov 2026 00:16:00 +0900 Subject: [PATCH] XMC finalmask: Make startup `paddings` configurable (`direction`, `length` and `delay`) (#6769) https://github.com/XTLS/Xray-core/pull/6487#issuecomment-5008140264 https://github.com/XTLS/Xray-core/pull/6769#issuecomment-5861391675 https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6056420905 https://github.com/XTLS/Xray-core/issues/7394#issuecomment-6876480694 https://github.com/XTLS/Xray-core/pull/7401#issuecomment-6876702404 https://github.com/XTLS/Xray-core/pull/6769#issuecomment-6876963752 Closes https://github.com/XTLS/Xray-core/issues/6732#issuecomment-5575293343 --------- Co-authored-by: RPRX <63339210+RPRX@users.noreply.github.com> --- infra/conf/transport_finalmask.go | 51 +- infra/conf/transport_finalmask_xmc_test.go | 53 ++ transport/internet/finalmask/xmc/client.go | 4 +- transport/internet/finalmask/xmc/config.go | 56 +- transport/internet/finalmask/xmc/config.pb.go | 107 ++- transport/internet/finalmask/xmc/config.proto | 11 + .../internet/finalmask/xmc/deadline_test.go | 81 --- .../internet/finalmask/xmc/derivation_test.go | 58 -- .../internet/finalmask/xmc/handshake_test.go | 390 ----------- .../finalmask/xmc/packet_stream_test.go | 102 --- transport/internet/finalmask/xmc/padding.go | 7 +- .../internet/finalmask/xmc/padding_test.go | 618 ------------------ .../internet/finalmask/xmc/profile_test.go | 33 - .../internet/finalmask/xmc/protocol_test.go | 56 -- transport/internet/finalmask/xmc/server.go | 4 +- .../internet/finalmask/xmc/stream_test.go | 81 --- 16 files changed, 265 insertions(+), 1447 deletions(-) delete mode 100644 transport/internet/finalmask/xmc/deadline_test.go delete mode 100644 transport/internet/finalmask/xmc/derivation_test.go delete mode 100644 transport/internet/finalmask/xmc/handshake_test.go delete mode 100644 transport/internet/finalmask/xmc/packet_stream_test.go delete mode 100644 transport/internet/finalmask/xmc/padding_test.go delete mode 100644 transport/internet/finalmask/xmc/profile_test.go delete mode 100644 transport/internet/finalmask/xmc/protocol_test.go delete mode 100644 transport/internet/finalmask/xmc/stream_test.go diff --git a/infra/conf/transport_finalmask.go b/infra/conf/transport_finalmask.go index 6f3292313..c553b3427 100644 --- a/infra/conf/transport_finalmask.go +++ b/infra/conf/transport_finalmask.go @@ -932,9 +932,16 @@ func (c *XDNS) Build() (proto.Message, error) { } type XMC struct { - Hostname string `json:"hostname"` - Profiles []XMCProfile `json:"profiles"` - Password string `json:"password"` + Hostname string `json:"hostname"` + Profiles []XMCProfile `json:"profiles"` + Password string `json:"password"` + Paddings []XMCPaddingTurn `json:"paddings,omitempty"` +} + +type XMCPaddingTurn struct { + Length string `json:"length"` + Direction string `json:"direction"` + Delay int64 `json:"delay,omitempty"` } type XMCProfile struct { @@ -977,6 +984,33 @@ func (c *XMC) Build() (proto.Message, error) { if c.Password == "" { return nil, fmt.Errorf("empty password") } + config := &xmc.Config{Password: c.Password, Hostname: c.Hostname} + for i, turn := range c.Paddings { + minimum, maximum, err := ParseRangeString(turn.Length) + if err != nil { + return nil, fmt.Errorf("minecraft padding turn %d: %w", i, err) + } + + var direction int32 + switch turn.Direction { + case "c2s", "client-to-server": + direction = 1 + case "s2c", "server-to-client": + direction = 2 + default: + return nil, fmt.Errorf("minecraft padding turn %d: invalid direction %q (must be \"c2s\" or \"s2c\")", i, turn.Direction) + } + + config.Paddings = append(config.Paddings, &xmc.Padding{ + LengthMin: int64(minimum), + LengthMax: int64(maximum), + Direction: direction, + Delay: turn.Delay, + }) + } + if err := config.ValidatePadding(); err != nil { + return nil, fmt.Errorf("minecraft padding: %w", err) + } rsaPrivateKey, err := xmc.DeriveRSAKey(c.Password) if err != nil { @@ -997,13 +1031,10 @@ func (c *XMC) Build() (proto.Message, error) { profiles = append(profiles, profile) } - return &xmc.Config{ - Password: c.Password, - Hostname: c.Hostname, - RsaPrivateKey: x509.MarshalPKCS1PrivateKey(rsaPrivateKey), - RsaPublicKey: rsaPublicKey, - Profiles: profiles, - }, nil + config.RsaPrivateKey = x509.MarshalPKCS1PrivateKey(rsaPrivateKey) + config.RsaPublicKey = rsaPublicKey + config.Profiles = profiles + return config, nil } type Xicmp struct { diff --git a/infra/conf/transport_finalmask_xmc_test.go b/infra/conf/transport_finalmask_xmc_test.go index 5d4257456..db1a31a30 100644 --- a/infra/conf/transport_finalmask_xmc_test.go +++ b/infra/conf/transport_finalmask_xmc_test.go @@ -1,6 +1,7 @@ package conf import ( + "encoding/json" "strings" "testing" @@ -10,6 +11,11 @@ import ( func TestXMCBuildProfile(t *testing.T) { built, err := (&XMC{ Password: "test-password", + Paddings: []XMCPaddingTurn{ + {Length: "3", Direction: "c2s", Delay: 0}, + {Length: "127-129", Direction: "s2c", Delay: 100}, + {Length: "8388608", Direction: "c2s", Delay: 50}, + }, Profiles: []XMCProfile{ { Username: "TestUser", @@ -26,6 +32,17 @@ func TestXMCBuildProfile(t *testing.T) { if len(config.Profiles) != 1 || len(config.Profiles[0].Uuid) != 16 { t.Fatalf("unexpected profiles: %+v", config.Profiles) } + if len(config.Paddings) != 3 || config.Paddings[0].LengthMin != 3 || config.Paddings[0].LengthMax != 3 || + config.Paddings[1].LengthMin != 127 || config.Paddings[1].LengthMax != 129 || + config.Paddings[2].LengthMin != 8388608 || config.Paddings[2].LengthMax != 8388608 { + t.Fatalf("unexpected padding: %v", config.Paddings) + } + if config.Paddings[0].Direction != 1 || config.Paddings[1].Direction != 2 || config.Paddings[2].Direction != 1 { + t.Fatalf("unexpected padding directions: %v, %v, %v", config.Paddings[0].Direction, config.Paddings[1].Direction, config.Paddings[2].Direction) + } + if config.Paddings[0].Delay != 0 || config.Paddings[1].Delay != 100 || config.Paddings[2].Delay != 50 { + t.Fatalf("unexpected padding delays: %v, %v, %v", config.Paddings[0].Delay, config.Paddings[1].Delay, config.Paddings[2].Delay) + } } func TestXMCBuildRequiresProfile(t *testing.T) { @@ -34,3 +51,39 @@ func TestXMCBuildRequiresProfile(t *testing.T) { t.Fatalf("expected required profiles error, got %v", err) } } + +func TestXMCBuildRejectsPadding(t *testing.T) { + for name, padding := range map[string]string{ + "empty_length": `[{"length": "", "direction": "c2s"}]`, + "zero_length": `[{"length": "0", "direction": "c2s"}]`, + "one_length": `[{"length": "1", "direction": "c2s"}]`, + "two_length": `[{"length": "2", "direction": "c2s"}]`, + "negative_length": `[{"length": "-1", "direction": "c2s"}]`, + "reversed_range": `[{"length": "64-32", "direction": "c2s"}]`, + "oversized_length": `[{"length": "8388609", "direction": "c2s"}]`, + "huge_length": `[{"length": "4294967299", "direction": "c2s"}]`, + "overflow_length": `[{"length": "9223372036854775808", "direction": "c2s"}]`, + "invalid_range_format": `[{"length": "1-2-3", "direction": "c2s"}]`, + "invalid_direction": `[{"length": "3", "direction": "invalid"}]`, + "missing_direction": `[{"length": "3"}]`, + "numeric_direction": `[{"length": "3", "direction": "1"}]`, + "negative_delay": `[{"length": "3", "direction": "c2s", "delay": -1}]`, + } { + t.Run(name, func(t *testing.T) { + var config XMC + if err := json.Unmarshal([]byte(`{"paddings":`+padding+`}`), &config); err != nil { + t.Fatal(err) + } + config.Password = "test-password" + config.Profiles = []XMCProfile{{ + Username: "TestUser", UUID: "00112233-4455-6677-8899-aabbccddeeff", + TexturesValue: "textures-value", TexturesSignature: "textures-signature", + }} + if _, err := config.Build(); err == nil { + t.Fatalf("expected error for padding %s, got success", padding) + } else { + t.Logf("correctly rejected: %v", err) + } + }) + } +} diff --git a/transport/internet/finalmask/xmc/client.go b/transport/internet/finalmask/xmc/client.go index 6159d09a1..eecb2a09b 100644 --- a/transport/internet/finalmask/xmc/client.go +++ b/transport/internet/finalmask/xmc/client.go @@ -41,14 +41,14 @@ var ( clientStateProxy clientState = 2 ) -func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string) (*clientConn, error) { +func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, padding []*Padding) (*clientConn, error) { if len(rsaPublicKey) == 0 { return nil, fmt.Errorf("empty rsa public key") } if len(profiles) == 0 { return nil, fmt.Errorf("empty profiles") } - paddingSchedule, err := newClientPaddingSchedule2612() + paddingSchedule, err := newPaddingSchedule(padding, true) if err != nil { return nil, fmt.Errorf("select padding profile: %w", err) } diff --git a/transport/internet/finalmask/xmc/config.go b/transport/internet/finalmask/xmc/config.go index 8ee16b2e4..c33447cc7 100644 --- a/transport/internet/finalmask/xmc/config.go +++ b/transport/internet/finalmask/xmc/config.go @@ -12,7 +12,7 @@ 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) + cc, err := newClientConn(conn, profiles, c.Password, c.RsaPublicKey, c.Hostname, c.Paddings) if err != nil { return nil, fmt.Errorf("minecraft finalmask: %w", err) } @@ -25,10 +25,62 @@ 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) + cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, c.Paddings) if err != nil { return nil, fmt.Errorf("minecraft finalmask: %w", err) } return cc, nil } + +// ValidatePadding checks custom startup turns without selecting a built-in preset. +func (c *Config) ValidatePadding() error { + _, err := paddingScheduleFromConfig(c.Paddings) + return err +} + +func paddingScheduleFromConfig(paddings []*Padding) ([]paddingTurn, error) { + if len(paddings) == 0 { + return nil, nil + } + schedule := make([]paddingTurn, len(paddings)) + for i, turn := range paddings { + if turn == nil || turn.LengthMin < 1 || turn.LengthMax < turn.LengthMin || turn.LengthMax > maxPaddingTurnLength { + return nil, fmt.Errorf("invalid padding length range at turn %d", i) + } + if turn.Delay < 0 { + return nil, fmt.Errorf("invalid padding delay %d at turn %d (must be non-negative)", turn.Delay, i) + } + var direction paddingDirection + switch turn.Direction { + case 1: + direction = paddingClientToServer + case 2: + direction = paddingServerToClient + default: + return nil, fmt.Errorf("invalid padding direction %d at turn %d (1=client-to-server, 2=server-to-client)", turn.Direction, i) + } + schedule[i] = paddingTurn{ + direction: direction, + minLength: int(turn.LengthMin), + maxLength: int(turn.LengthMax), + delay: int(turn.Delay), + } + } + // The first turn includes the two-byte Login Acknowledged packet. + if err := validatePaddingSchedule(schedule, 2); err != nil { + return nil, err + } + 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() +} diff --git a/transport/internet/finalmask/xmc/config.pb.go b/transport/internet/finalmask/xmc/config.pb.go index 0f670ea9d..a707eee94 100644 --- a/transport/internet/finalmask/xmc/config.pb.go +++ b/transport/internet/finalmask/xmc/config.pb.go @@ -99,6 +99,8 @@ 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"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -168,6 +170,83 @@ func (x *Config) GetProfiles() []*Profile { return nil } +func (x *Config) GetPaddings() []*Padding { + if x != nil { + return x.Paddings + } + return nil +} + +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"` + // Delay in milliseconds after sending this turn + Delay int64 `protobuf:"varint,4,opt,name=delay,proto3" json:"delay,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Padding) Reset() { + *x = Padding{} + mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Padding) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Padding) ProtoMessage() {} + +func (x *Padding) ProtoReflect() protoreflect.Message { + mi := &file_transport_internet_finalmask_xmc_config_proto_msgTypes[2] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Padding.ProtoReflect.Descriptor instead. +func (*Padding) Descriptor() ([]byte, []int) { + return file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP(), []int{2} +} + +func (x *Padding) GetLengthMin() int64 { + if x != nil { + return x.LengthMin + } + return 0 +} + +func (x *Padding) GetLengthMax() int64 { + if x != nil { + return x.LengthMax + } + return 0 +} + +func (x *Padding) GetDirection() int32 { + if x != nil { + return x.Direction + } + return 0 +} + +func (x *Padding) GetDelay() int64 { + if x != nil { + return x.Delay + } + return 0 +} + var File_transport_internet_finalmask_xmc_config_proto protoreflect.FileDescriptor const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" + @@ -177,14 +256,22 @@ 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\"\xe0\x01\n" + + "\x12textures_signature\x18\x04 \x01(\tR\x11texturesSignature\"\xac\x02\n" + "\x06Config\x12\x1a\n" + "\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" + "\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" + "\x0ersa_public_key\x18\t \x01(\fR\frsaPublicKey\x12\x1a\n" + "\bhostname\x18\n" + " \x01(\tR\bhostname\x12J\n" + - "\bprofiles\x18\v \x03(\v2..xray.transport.internet.finalmask.xmc.ProfileR\bprofilesJ\x04\b\x02\x10\x03B\x91\x01\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\"{\n" + + "\aPadding\x12\x1d\n" + + "\n" + + "length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" + + "\n" + + "length_max\x18\x02 \x01(\x03R\tlengthMax\x12\x1c\n" + + "\tdirection\x18\x03 \x01(\x05R\tdirection\x12\x14\n" + + "\x05delay\x18\x04 \x01(\x03R\x05delayB\x91\x01\n" + ")com.xray.transport.internet.finalmask.xmcP\x01Z:github.com/xtls/xray-core/transport/internet/finalmask/xmc\xaa\x02%Xray.Transport.Internet.Finalmask.XMCb\x06proto3" var ( @@ -199,18 +286,20 @@ func file_transport_internet_finalmask_xmc_config_proto_rawDescGZIP() []byte { return file_transport_internet_finalmask_xmc_config_proto_rawDescData } -var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_transport_internet_finalmask_xmc_config_proto_msgTypes = make([]protoimpl.MessageInfo, 3) var file_transport_internet_finalmask_xmc_config_proto_goTypes = []any{ (*Profile)(nil), // 0: xray.transport.internet.finalmask.xmc.Profile (*Config)(nil), // 1: xray.transport.internet.finalmask.xmc.Config + (*Padding)(nil), // 2: xray.transport.internet.finalmask.xmc.Padding } var file_transport_internet_finalmask_xmc_config_proto_depIdxs = []int32{ 0, // 0: xray.transport.internet.finalmask.xmc.Config.profiles:type_name -> xray.transport.internet.finalmask.xmc.Profile - 1, // [1:1] is the sub-list for method output_type - 1, // [1:1] is the sub-list for method input_type - 1, // [1:1] is the sub-list for extension type_name - 1, // [1:1] is the sub-list for extension extendee - 0, // [0:1] is the sub-list for field type_name + 2, // 1: xray.transport.internet.finalmask.xmc.Config.paddings:type_name -> xray.transport.internet.finalmask.xmc.Padding + 2, // [2:2] is the sub-list for method output_type + 2, // [2:2] is the sub-list for method input_type + 2, // [2:2] is the sub-list for extension type_name + 2, // [2:2] is the sub-list for extension extendee + 0, // [0:2] is the sub-list for field type_name } func init() { file_transport_internet_finalmask_xmc_config_proto_init() } @@ -224,7 +313,7 @@ func file_transport_internet_finalmask_xmc_config_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_transport_internet_finalmask_xmc_config_proto_rawDesc), len(file_transport_internet_finalmask_xmc_config_proto_rawDesc)), NumEnums: 0, - NumMessages: 2, + NumMessages: 3, NumExtensions: 0, NumServices: 0, }, diff --git a/transport/internet/finalmask/xmc/config.proto b/transport/internet/finalmask/xmc/config.proto index c880439d0..de8c6d5bc 100644 --- a/transport/internet/finalmask/xmc/config.proto +++ b/transport/internet/finalmask/xmc/config.proto @@ -23,4 +23,15 @@ message Config { bytes rsa_public_key = 9; string hostname = 10; repeated Profile profiles = 11; + // Startup padding turns. Empty uses the built-in preset. + repeated Padding paddings = 12; +} + +message Padding { + int64 length_min = 1; + int64 length_max = 2; + // 1 = client to server, 2 = server to client + int32 direction = 3; + // Delay in milliseconds after sending this turn + int64 delay = 4; } diff --git a/transport/internet/finalmask/xmc/deadline_test.go b/transport/internet/finalmask/xmc/deadline_test.go deleted file mode 100644 index 2a56c3e2c..000000000 --- a/transport/internet/finalmask/xmc/deadline_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package xmc - -import ( - "net" - "sync" - "testing" - "time" -) - -func TestConnectionDeadlinesRestoreCallerValues(t *testing.T) { - client, server := net.Pipe() - defer client.Close() - defer server.Close() - - recording := &deadlineRecordingConn{Conn: client} - deadlines := newConnectionDeadlines(recording) - callerDeadline := time.Now().Add(10 * time.Minute) - if err := deadlines.setDeadline(callerDeadline); err != nil { - t.Fatal(err) - } - if err := deadlines.beginHandshake(); err != nil { - t.Fatal(err) - } - - read, write := recording.currentDeadlines() - if !read.Before(callerDeadline) || !write.Before(callerDeadline) { - t.Fatalf("handshake deadlines = %s/%s, caller = %s", read, write, callerDeadline) - } - - shortReadDeadline := time.Now().Add(time.Second) - if err := deadlines.setReadDeadline(shortReadDeadline); err != nil { - t.Fatal(err) - } - read, _ = recording.currentDeadlines() - if !read.Equal(shortReadDeadline) { - t.Fatalf("read deadline = %s, want %s", read, shortReadDeadline) - } - - if err := deadlines.endHandshake(); err != nil { - t.Fatal(err) - } - read, write = recording.currentDeadlines() - if !read.Equal(shortReadDeadline) || !write.Equal(callerDeadline) { - t.Fatalf("restored deadlines = %s/%s, want %s/%s", read, write, shortReadDeadline, callerDeadline) - } -} - -type deadlineRecordingConn struct { - net.Conn - mu sync.Mutex - read time.Time - write time.Time -} - -func (c *deadlineRecordingConn) SetDeadline(t time.Time) error { - c.mu.Lock() - c.read = t - c.write = t - c.mu.Unlock() - return c.Conn.SetDeadline(t) -} - -func (c *deadlineRecordingConn) SetReadDeadline(t time.Time) error { - c.mu.Lock() - c.read = t - c.mu.Unlock() - return c.Conn.SetReadDeadline(t) -} - -func (c *deadlineRecordingConn) SetWriteDeadline(t time.Time) error { - c.mu.Lock() - c.write = t - c.mu.Unlock() - return c.Conn.SetWriteDeadline(t) -} - -func (c *deadlineRecordingConn) currentDeadlines() (time.Time, time.Time) { - c.mu.Lock() - defer c.mu.Unlock() - return c.read, c.write -} diff --git a/transport/internet/finalmask/xmc/derivation_test.go b/transport/internet/finalmask/xmc/derivation_test.go deleted file mode 100644 index b436d46dc..000000000 --- a/transport/internet/finalmask/xmc/derivation_test.go +++ /dev/null @@ -1,58 +0,0 @@ -package xmc - -import ( - "crypto/sha256" - "crypto/x509" - "encoding/hex" - "testing" -) - -func TestDeriveRSAKey(t *testing.T) { - password := "my-very-secret-password-12345" - - key1, err := DeriveRSAKey(password) - if err != nil { - t.Fatalf("failed to derive key: %v", err) - } - - err = key1.Validate() - if err != nil { - t.Fatalf("key is not valid RSA key: %v", err) - } - - key2, err := DeriveRSAKey(password) - if err != nil { - t.Fatalf("failed to derive key second time: %v", err) - } - - // Verify determinism - if key1.D.Cmp(key2.D) != 0 || key1.N.Cmp(key2.N) != 0 { - t.Errorf("derived keys are not identical for the same password") - } - - // Verify different passwords yield different keys - keyDifferent, err := DeriveRSAKey(password + "-different") - if err != nil { - t.Fatalf("failed to derive different key: %v", err) - } - - if key1.D.Cmp(keyDifferent.D) == 0 || key1.N.Cmp(keyDifferent.N) == 0 { - t.Errorf("derived keys are identical for different passwords") - } -} - -func TestDeriveRSAKeyGoldenPrivateKey(t *testing.T) { - const password = "deterministic-rsa-key-golden" - const wantPKCS1DERHash = "3a8c4ad56a6fb42dab73c4d5fc3af754460a2db1441edc0970cbc7f4e0798d2f" - - key, err := DeriveRSAKey(password) - if err != nil { - t.Fatalf("failed to derive key: %v", err) - } - - gotHash := sha256.Sum256(x509.MarshalPKCS1PrivateKey(key)) - got := hex.EncodeToString(gotHash[:]) - if got != wantPKCS1DERHash { - t.Fatalf("derived private key changed\nwant sha256: %s\n got sha256: %s", wantPKCS1DERHash, got) - } -} diff --git a/transport/internet/finalmask/xmc/handshake_test.go b/transport/internet/finalmask/xmc/handshake_test.go deleted file mode 100644 index b2db51ef9..000000000 --- a/transport/internet/finalmask/xmc/handshake_test.go +++ /dev/null @@ -1,390 +0,0 @@ -package xmc - -import ( - "bytes" - "crypto/sha256" - "crypto/x509" - "errors" - "fmt" - "io" - "net" - "strings" - "sync" - "testing" - "time" -) - -func deriveTestRSAKey(t *testing.T, password string) ([]byte, []byte) { - t.Helper() - - key, err := DeriveRSAKey(password) - if err != nil { - t.Fatalf("failed to derive rsa key: %v", err) - } - - publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey) - if err != nil { - t.Fatalf("failed to marshal public key: %v", err) - } - - return x509.MarshalPKCS1PrivateKey(key), publicKey -} - -func testLoginProfile(username string) loginProfile { - profile := loginProfile{ - Username: username, - TexturesValue: strings.Repeat("texture-value-", 40), - TexturesSignature: strings.Repeat("texture-signature-", 24), - } - digest := sha256.Sum256([]byte(username)) - copy(profile.UUID[:], digest[:16]) - profile.UUID[6] = (profile.UUID[6] & 0x0f) | 0x40 - profile.UUID[8] = (profile.UUID[8] & 0x3f) | 0x80 - return profile -} - -func TestHandshakeSuccess(t *testing.T) { - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - defer ln.Close() - - password := "super-secure-shared-key-12345" - profiles := []loginProfile{testLoginProfile("test_user")} - privateKey, publicKey := deriveTestRSAKey(t, password) - - go func() { - rawConn, err := ln.Accept() - if err != nil { - return - } - defer rawConn.Close() - - server, err := wrapConnServer(rawConn, profiles, password, privateKey, publicKey) - if err != nil { - t.Errorf("failed to wrap server: %v", err) - return - } - - buf := make([]byte, 1024) - n, err := server.Read(buf) - if err != nil { - t.Errorf("server read error: %v", err) - return - } - - if !bytes.Equal(buf[:n], []byte("hello server")) { - t.Errorf("unexpected payload from client: %s", string(buf[:n])) - return - } - - _, err = server.Write([]byte("hello client")) - if err != nil { - t.Errorf("server write error: %v", err) - return - } - }() - - clientRaw, err := net.Dial("tcp", ln.Addr().String()) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer clientRaw.Close() - - client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost") - if err != nil { - t.Fatalf("failed to create client: %v", err) - } - - _, err = client.Write([]byte("hello server")) - if err != nil { - t.Fatalf("client write error: %v", err) - } - - buf := make([]byte, 1024) - n, err := client.Read(buf) - if err != nil { - t.Fatalf("client read error: %v", err) - } - - if !bytes.Equal(buf[:n], []byte("hello client")) { - t.Errorf("unexpected payload from server: %s", string(buf[:n])) - } -} - -func TestHandshakePasswordMismatch(t *testing.T) { - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("failed to listen: %v", err) - } - defer ln.Close() - - clientPassword := "client-secret-123" - serverPassword := "server-secret-456" - profiles := []loginProfile{testLoginProfile("test_user")} - serverPrivateKey, serverPublicKey := deriveTestRSAKey(t, serverPassword) - - var wg sync.WaitGroup - wg.Add(1) - go func() { - defer wg.Done() - - rawConn, err := ln.Accept() - if err != nil { - return - } - defer rawConn.Close() - - server, err := wrapConnServer(rawConn, profiles, serverPassword, serverPrivateKey, serverPublicKey) - if err != nil { - // Wrapping is synchronous and shouldn't fail initially simply because key derivation works with any string - t.Logf("wrapped server: %v", err) - } - - // When client sends data, handshake happens and should fail - buf := make([]byte, 1024) - _, err = server.Read(buf) - if err == nil { - t.Errorf("expected handshake to fail due to password mismatch, but it succeeded") - } else { - t.Logf("server read failed as expected: %v", err) - } - }() - - clientRaw, err := net.Dial("tcp", ln.Addr().String()) - if err != nil { - t.Fatalf("failed to dial: %v", err) - } - defer clientRaw.Close() - - client, err := newClientConn(clientRaw, profiles, clientPassword, serverPublicKey, "localhost") - if err != nil { - t.Fatalf("failed to create client: %v", err) - } - - err = client.handshake() - if err == nil { - t.Fatal("expected client handshake to fail due to password mismatch") - } - - wg.Wait() - - // Check if we lost connection or received error - t.Log("Handshake mismatch tested") -} - -func TestHandshakeNetPipeWithKeepAlive(t *testing.T) { - clientRaw, serverRaw := net.Pipe() - defer clientRaw.Close() - defer serverRaw.Close() - - const password = "net-pipe-shared-key" - profiles := []loginProfile{testLoginProfile("pipe_user")} - privateKey, publicKey := deriveTestRSAKey(t, password) - serverDone := make(chan error, 1) - - go func() { - server, err := wrapConnServer(serverRaw, profiles, password, privateKey, publicKey) - if err != nil { - serverDone <- err - return - } - - request := make([]byte, len("hello server")) - if _, err = io.ReadFull(server, request); err != nil { - serverDone <- fmt.Errorf("read request: %w", err) - return - } - if string(request) != "hello server" { - serverDone <- fmt.Errorf("unexpected request: %q", request) - return - } - - followupDone := make(chan error, 1) - go func() { - followup := make([]byte, len("after keepalive")) - _, readErr := io.ReadFull(server, followup) - if readErr == nil && string(followup) != "after keepalive" { - readErr = fmt.Errorf("unexpected followup: %q", followup) - } - followupDone <- readErr - }() - - if err = server.packet.writeKeepAlive(Long(42)); err != nil { - serverDone <- fmt.Errorf("write keep-alive: %w", err) - return - } - if _, err = server.Write([]byte("hello client")); err != nil { - serverDone <- fmt.Errorf("write response: %w", err) - return - } - serverDone <- <-followupDone - }() - - client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost") - if err != nil { - t.Fatal(err) - } - if _, err = client.Write([]byte("hello server")); err != nil { - t.Fatalf("write request: %v", err) - } - response := make([]byte, len("hello client")) - if _, err = io.ReadFull(client, response); err != nil { - t.Fatalf("read response: %v", err) - } - if string(response) != "hello client" { - t.Fatalf("unexpected response: %q", response) - } - if _, err = client.Write([]byte("after keepalive")); err != nil { - t.Fatalf("write followup: %v", err) - } - - select { - case err = <-serverDone: - if err != nil { - t.Fatal(err) - } - case <-time.After(5 * time.Second): - t.Fatal("net.Pipe handshake timed out") - } -} - -func TestStatusQueryUnaffected(t *testing.T) { - clientRaw, serverRaw := net.Pipe() - defer clientRaw.Close() - defer serverRaw.Close() - - const password = "status-shared-key" - profiles := []loginProfile{testLoginProfile("status_user")} - privateKey, publicKey := deriveTestRSAKey(t, password) - serverDone := make(chan error, 1) - go func() { - server, err := wrapConnServer(serverRaw, profiles, password, privateKey, publicKey) - if err == nil { - err = server.handshake() - } - serverDone <- err - }() - - protocolVersion := Varint(775) - serverAddress := String("localhost") - serverPort := UnsignedShort(25565) - nextState := Varint(1) - if err := writePacket(clientRaw, 0x00, &protocolVersion, &serverAddress, &serverPort, &nextState); err != nil { - t.Fatal(err) - } - if err := writePacket(clientRaw, 0x00); err != nil { - t.Fatal(err) - } - response, err := readPacket(clientRaw) - if err != nil { - t.Fatal(err) - } - if response.packetID != 0x00 { - t.Fatalf("status packet id = %d", response.packetID) - } - var responseJSON String - if err = response.readFields(&responseJSON); err != nil { - t.Fatal(err) - } - if string(responseJSON) != statusResponse { - t.Fatalf("status response = %q", responseJSON) - } - - payload := Long(0x0102030405060708) - if err = writePacket(clientRaw, 0x01, &payload); err != nil { - t.Fatal(err) - } - pong, err := readPacket(clientRaw) - if err != nil { - t.Fatal(err) - } - var receivedPayload Long - if pong.packetID != 0x01 { - t.Fatalf("pong packet id = %d", pong.packetID) - } - if err = pong.readFields(&receivedPayload); err != nil { - t.Fatal(err) - } - if receivedPayload != payload { - t.Fatalf("pong payload = %x", receivedPayload) - } - - select { - case err = <-serverDone: - if err == nil || !strings.Contains(err.Error(), "ping") { - t.Fatalf("server error = %v", err) - } - case <-time.After(time.Second): - t.Fatal("status handshake timed out") - } -} - -func TestClientHandshakeHonorsCallerDeadline(t *testing.T) { - clientRaw, serverRaw := net.Pipe() - defer clientRaw.Close() - defer serverRaw.Close() - - const password = "deadline-shared-key" - profiles := []loginProfile{testLoginProfile("deadline_user")} - _, publicKey := deriveTestRSAKey(t, password) - client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost") - if err != nil { - t.Fatal(err) - } - if err = client.SetDeadline(time.Now().Add(30 * time.Millisecond)); err != nil { - t.Fatal(err) - } - - started := time.Now() - _, err = client.Write([]byte("blocked")) - var netErr net.Error - if !errors.As(err, &netErr) || !netErr.Timeout() { - t.Fatalf("error = %v, want network timeout", err) - } - if elapsed := time.Since(started); elapsed > 500*time.Millisecond { - t.Fatalf("caller deadline took %s", elapsed) - } -} - -func TestClientCloseInterruptsHandshake(t *testing.T) { - clientRaw, serverRaw := net.Pipe() - defer serverRaw.Close() - - const password = "close-shared-key" - profiles := []loginProfile{testLoginProfile("close_user")} - _, publicKey := deriveTestRSAKey(t, password) - client, err := newClientConn(clientRaw, profiles, password, publicKey, "localhost") - if err != nil { - t.Fatal(err) - } - - done := make(chan error, 1) - go func() { - _, writeErr := client.Write([]byte("blocked")) - done <- writeErr - }() - time.Sleep(20 * time.Millisecond) - if err = client.Close(); err != nil { - t.Fatal(err) - } - - select { - case err = <-done: - if err == nil { - t.Fatal("handshake unexpectedly succeeded after close") - } - case <-time.After(time.Second): - t.Fatal("close did not interrupt handshake") - } -} - -func TestValidateLoginAcknowledgedPacketRejectsData(t *testing.T) { - if err := validateLoginAcknowledgedPacket(&mcPacket{packetID: 0x03}); err != nil { - t.Fatalf("valid login acknowledged packet: %v", err) - } - if err := validateLoginAcknowledgedPacket(&mcPacket{packetID: 0x03, data: []byte{0x00}}); err == nil { - t.Fatal("login acknowledged packet with trailing data was accepted") - } -} diff --git a/transport/internet/finalmask/xmc/packet_stream_test.go b/transport/internet/finalmask/xmc/packet_stream_test.go deleted file mode 100644 index ea605249f..000000000 --- a/transport/internet/finalmask/xmc/packet_stream_test.go +++ /dev/null @@ -1,102 +0,0 @@ -package xmc - -import ( - "bytes" - "io" - "net" - "testing" -) - -func TestPacketStreamUsesPlainFraming(t *testing.T) { - payload := []byte("hello") - var wire bytes.Buffer - stream := newPacketStream(bytes.NewReader(nil), &wire, true) - - written, err := stream.Write(payload) - if err != nil { - t.Fatalf("write payload: %v", err) - } - if written != len(payload) { - t.Fatalf("written = %d, want %d", written, len(payload)) - } - wantOutbound := []byte{0x0f, 0x02, 0x08, 'x', 'm', 'c', ':', 'd', 'a', 't', 'a', 'h', 'e', 'l', 'l', 'o'} - if !bytes.Equal(wire.Bytes(), wantOutbound) { - t.Fatalf("wire frame = %x, want %x", wire.Bytes(), wantOutbound) - } - - wantInbound := append([]byte(nil), wantOutbound...) - wantInbound[1] = configurationClientboundCustomPayload - reader := newPacketStream(bytes.NewReader(wantInbound), io.Discard, true) - got := make([]byte, len(payload)) - if _, err = io.ReadFull(reader, got); err != nil { - t.Fatalf("read payload: %v", err) - } - if !bytes.Equal(got, payload) { - t.Fatalf("payload = %q, want %q", got, payload) - } -} - -func TestPacketStreamRoundTrip(t *testing.T) { - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatal(err) - } - defer ln.Close() - - const password = "packet-stream-shared-key" - privateKey, publicKey := deriveTestRSAKey(t, password) - profiles := []loginProfile{testLoginProfile("packet_user")} - clientPayload := bytes.Repeat([]byte("client-payload-"), 5000) - serverPayload := bytes.Repeat([]byte("server-payload-"), 5000) - serverDone := make(chan error, 1) - - go func() { - rawConn, acceptErr := ln.Accept() - if acceptErr != nil { - serverDone <- acceptErr - return - } - defer rawConn.Close() - - server, wrapErr := wrapConnServer(rawConn, profiles, password, privateKey, publicKey) - if wrapErr != nil { - serverDone <- wrapErr - return - } - got := make([]byte, len(clientPayload)) - if _, readErr := io.ReadFull(server, got); readErr != nil { - serverDone <- readErr - return - } - if !bytes.Equal(got, clientPayload) { - serverDone <- io.ErrUnexpectedEOF - return - } - _, writeErr := server.Write(serverPayload) - serverDone <- writeErr - }() - - rawClient, err := net.Dial("tcp", ln.Addr().String()) - if err != nil { - t.Fatal(err) - } - defer rawClient.Close() - - client, err := newClientConn(rawClient, profiles, password, publicKey, "localhost") - if err != nil { - t.Fatal(err) - } - if _, err = client.Write(clientPayload); err != nil { - t.Fatalf("write payload: %v", err) - } - got := make([]byte, len(serverPayload)) - if _, err = io.ReadFull(client, got); err != nil { - t.Fatalf("read payload: %v", err) - } - if !bytes.Equal(got, serverPayload) { - t.Fatal("server payload mismatch") - } - if err = <-serverDone; err != nil { - t.Fatalf("server: %v", err) - } -} diff --git a/transport/internet/finalmask/xmc/padding.go b/transport/internet/finalmask/xmc/padding.go index eb7114a09..2343c440b 100644 --- a/transport/internet/finalmask/xmc/padding.go +++ b/transport/internet/finalmask/xmc/padding.go @@ -34,6 +34,7 @@ type paddingTurn struct { direction paddingDirection minLength int maxLength int + delay int // milliseconds delay after sending this turn variants []paddingVariant startDelay paddingDelayRange chunkDelay paddingDelayRange @@ -61,6 +62,9 @@ func runPaddingSchedule(reader io.Reader, writer io.Writer, isClient bool, first if err := writePaddingTurnWithBuffer(writer, turn, prefixLength, time.Sleep, &writeBuffer); err != nil { return fmt.Errorf("write padding turn %d: %w", i, err) } + if turn.delay > 0 { + time.Sleep(time.Duration(turn.delay) * time.Millisecond) + } continue } if err := readPaddingTurn(reader, turn, prefixLength); err != nil { @@ -121,9 +125,6 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int) } } } - if i > 0 && turn.direction == schedule[i-1].direction { - return fmt.Errorf("padding turns %d and %d have the same direction", i-1, i) - } } return nil } diff --git a/transport/internet/finalmask/xmc/padding_test.go b/transport/internet/finalmask/xmc/padding_test.go deleted file mode 100644 index 493306aaa..000000000 --- a/transport/internet/finalmask/xmc/padding_test.go +++ /dev/null @@ -1,618 +0,0 @@ -package xmc - -import ( - "bytes" - "errors" - "io" - "net" - "strconv" - "strings" - "testing" - "time" -) - -func TestPaddingTurnReachesFinalTargetLength(t *testing.T) { - turn := paddingTurn{direction: paddingClientToServer, minLength: 128, maxLength: 128} - const prefixLength = 3 - var encoded bytes.Buffer - if err := writePaddingTurn(&encoded, turn, prefixLength); err != nil { - t.Fatal(err) - } - if got := prefixLength + encoded.Len(); got != turn.minLength { - t.Fatalf("total turn length = %d, want %d", got, turn.minLength) - } - encodedReader := bytes.NewReader(encoded.Bytes()) - var recordLength Varint - if err := recordLength.readFrom(encodedReader); err != nil { - t.Fatal(err) - } - if got := int(recordLength); got != encoded.Len() { - t.Fatalf("record length = %d, encoded = %d", got, encoded.Len()) - } - if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, prefixLength); err != nil { - t.Fatal(err) - } -} - -func TestPaddingTurnSupportsThreeByteTarget(t *testing.T) { - turn := paddingTurn{direction: paddingClientToServer, minLength: 3, maxLength: 3} - var encoded bytes.Buffer - if err := writePaddingTurn(&encoded, turn, 0); err != nil { - t.Fatal(err) - } - if got := encoded.Len(); got != 3 { - t.Fatalf("padding length = %d, want 3", got) - } - if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil { - t.Fatal(err) - } -} - -func TestPaddingTurnVarintBoundaries(t *testing.T) { - for _, targetLength := range []int{127, 128, 16383, 16384} { - t.Run(strconv.Itoa(targetLength), func(t *testing.T) { - turn := paddingTurn{direction: paddingClientToServer, minLength: targetLength, maxLength: targetLength} - var encoded bytes.Buffer - if err := writePaddingTurn(&encoded, turn, 0); err != nil { - t.Fatal(err) - } - if encoded.Len() != targetLength { - t.Fatalf("padding length = %d, want %d", encoded.Len(), targetLength) - } - if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil { - t.Fatal(err) - } - }) - } -} - -func TestPaddingTurnRandomRange(t *testing.T) { - turn := paddingTurn{direction: paddingServerToClient, minLength: 127, maxLength: 129} - seen := make(map[int]bool) - for range 100 { - var encoded bytes.Buffer - if err := writePaddingTurn(&encoded, turn, 0); err != nil { - t.Fatal(err) - } - if encoded.Len() < turn.minLength || encoded.Len() > turn.maxLength { - t.Fatalf("padding length = %d", encoded.Len()) - } - seen[encoded.Len()] = true - } - if len(seen) < 2 { - t.Fatalf("padding range did not vary: %v", seen) - } -} - -func TestPaddingTurnUsesRestrictedSendRange(t *testing.T) { - turn := paddingTurn{ - direction: paddingServerToClient, - minLength: 3, - maxLength: 100, - sendMinLength: 90, - sendMaxLength: 100, - } - seen := make(map[int]bool) - for range 100 { - var encoded bytes.Buffer - if err := writePaddingTurn(&encoded, turn, 0); err != nil { - t.Fatal(err) - } - if encoded.Len() < turn.sendMinLength || encoded.Len() > turn.sendMaxLength { - t.Fatalf("padding length = %d", encoded.Len()) - } - seen[encoded.Len()] = true - if err := readPaddingTurn(bytes.NewReader(encoded.Bytes()), turn, 0); err != nil { - t.Fatal(err) - } - } - if len(seen) < 2 { - t.Fatalf("restricted send range did not vary: %v", seen) - } -} - -func TestPaddingScheduleSynchronizesDirections(t *testing.T) { - client, server := net.Pipe() - defer client.Close() - defer server.Close() - - schedule := []paddingTurn{ - {direction: paddingClientToServer, minLength: 33, maxLength: 33}, - {direction: paddingServerToClient, minLength: 4097, maxLength: 4097}, - {direction: paddingClientToServer, minLength: 16385, maxLength: 16385}, - } - serverDone := make(chan error, 1) - go func() { - serverDone <- runPaddingSchedule(server, server, false, 3, schedule) - }() - if err := runPaddingSchedule(client, client, true, 3, schedule); err != nil { - t.Fatal(err) - } - select { - case err := <-serverDone: - if err != nil { - t.Fatal(err) - } - case <-time.After(time.Second): - t.Fatal("server padding schedule did not complete") - } -} - -func TestReadPaddingTurnHandlesFragmentedInput(t *testing.T) { - turn := paddingTurn{direction: paddingClientToServer, minLength: 1024, maxLength: 1024} - var encoded bytes.Buffer - if err := writePaddingTurn(&encoded, turn, 0); err != nil { - t.Fatal(err) - } - if err := readPaddingTurn(&oneByteReader{reader: bytes.NewReader(encoded.Bytes())}, turn, 0); err != nil { - t.Fatal(err) - } -} - -func TestReadPaddingTurnRejectsInvalidLength(t *testing.T) { - turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 96} - data := encodePaddingLength(t, 63) - if err := readPaddingTurn(bytes.NewReader(data), turn, 0); err == nil || !strings.Contains(err.Error(), "outside") { - t.Fatalf("error = %v", err) - } -} - -func TestReadPaddingTurnRejectsNonCanonicalHeader(t *testing.T) { - turn := paddingTurn{direction: paddingClientToServer, minLength: 3, maxLength: 3} - err := readPaddingTurn(bytes.NewReader([]byte{0x83, 0x00, 0x00}), turn, 0) - if err == nil || !strings.Contains(err.Error(), "non-canonical") { - t.Fatalf("error = %v", err) - } -} - -func TestReadPaddingTurnRejectsTruncatedBody(t *testing.T) { - turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 64} - data := encodePaddingLength(t, 64) - if err := readPaddingTurn(bytes.NewReader(data), turn, 0); err == nil || !strings.Contains(err.Error(), "body") { - t.Fatalf("error = %v", err) - } -} - -func TestReadPaddingTurnHonorsConnectionTimeout(t *testing.T) { - client, server := net.Pipe() - defer client.Close() - defer server.Close() - - if err := server.SetReadDeadline(time.Now().Add(20 * time.Millisecond)); err != nil { - t.Fatal(err) - } - turn := paddingTurn{direction: paddingClientToServer, minLength: 64, maxLength: 64} - err := readPaddingTurn(server, turn, 0) - var netErr net.Error - if !errors.As(err, &netErr) || !netErr.Timeout() { - t.Fatalf("error = %v, want network timeout", err) - } -} - -func TestValidatePaddingSchedule(t *testing.T) { - tests := []struct { - name string - schedule []paddingTurn - prefix int - }{ - {name: "empty"}, - {name: "bad direction", schedule: []paddingTurn{{direction: 99, minLength: 4, maxLength: 4}}}, - {name: "too small", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 0, maxLength: 4}}}, - {name: "reversed range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 7}}}, - {name: "wrong first direction", prefix: 3, schedule: []paddingTurn{{direction: paddingServerToClient, minLength: 8, maxLength: 8}}}, - {name: "prefix leaves no header", prefix: 8, schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8}}}, - {name: "same direction", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8}, {direction: paddingClientToServer, minLength: 8, maxLength: 8}}}, - {name: "range with variants", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, variants: []paddingVariant{paddingVariantFromChunks(8)}}}}, - {name: "empty variant", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{{}}}}}, - {name: "bad chunk", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(maxPaddingChunkLength + 1)}}}}, - { - name: "delay mismatch", - schedule: []paddingTurn{{ - direction: paddingClientToServer, - variants: []paddingVariant{{ - chunks: []int{4, 4}, - delays: []paddingDelayRange{{min: time.Millisecond, max: time.Millisecond}}, - }}, - }}, - }, - {name: "reversed start delay", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, startDelay: paddingDelayRange{min: 2 * time.Millisecond, max: time.Millisecond}}}}, - {name: "reversed generated chunk delay", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, chunkDelay: paddingDelayRange{min: 2 * time.Millisecond, max: time.Millisecond}}}}, - {name: "oversized generated chunk", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, writeChunkLength: maxPaddingChunkLength + 1}}}, - {name: "reversed generated chunk range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 8, writeChunkMinLength: 9, writeChunkLength: 8}}}, - {name: "variant with generated chunks", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, writeChunkLength: 8}}}, - {name: "send range outside accepted range", schedule: []paddingTurn{{direction: paddingClientToServer, minLength: 8, maxLength: 16, sendMinLength: 7, sendMaxLength: 12}}}, - {name: "variant with send range", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, sendMinLength: 8, sendMaxLength: 8}}}, - {name: "negative chunk delay", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{{chunks: []int{8}, delays: []paddingDelayRange{{min: -time.Millisecond}}}}}}}, - {name: "bad send variant", schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8)}, sendVariants: []int{1}}}}, - {name: "prefix splits chunk", prefix: 3, schedule: []paddingTurn{{direction: paddingClientToServer, variants: []paddingVariant{paddingVariantFromChunks(8, 4)}}}}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - if err := validatePaddingSchedule(test.schedule, test.prefix); err == nil { - t.Fatal("expected invalid padding schedule") - } - }) - } -} - -func TestPaddingSchedule2612MatchesCapturedTemplates(t *testing.T) { - wantDirections := []paddingDirection{ - paddingClientToServer, - paddingServerToClient, - paddingClientToServer, - paddingServerToClient, - paddingClientToServer, - paddingServerToClient, - } - wantLengths := [][]int{ - {44}, - {72}, - {25}, - {41172}, - {2}, - {7464, 8267, 8790, 8153, 7375, 7347, 8184, 6633, 7670, 8241, 7857, 7254, 8407, 8283, 6804, 8177, 8177, 7929, 8296, 8177}, - } - if len(paddingSchedule2612) != len(wantDirections)+33 { - t.Fatalf("padding schedule has %d turns, want %d", len(paddingSchedule2612), len(wantDirections)+33) - } - for i, turn := range paddingSchedule2612[:len(wantDirections)] { - if turn.direction != wantDirections[i] { - t.Fatalf("padding turn %d direction = %d, want %d", i, turn.direction, wantDirections[i]) - } - if len(turn.variants) != len(wantLengths[i]) { - t.Fatalf("padding turn %d has %d variants, want %d", i, len(turn.variants), len(wantLengths[i])) - } - for j, variant := range turn.variants { - if got := paddingVariantLength(variant); got != wantLengths[i][j] { - t.Fatalf("padding turn %d variant %d length = %d, want %d", i, j, got, wantLengths[i][j]) - } - } - } - wantPlayBounds := [][2]int{ - {6, 883}, - {346, 58638}, - {6, 887}, - {388, 61077}, - {2, 50}, - {575, 65584}, - {6, 45}, - {86, 63563}, - {2, 44}, - {42, 51983}, - {2, 851}, - {309, 25083}, - {2, 19}, - {74, 63885}, - {8, 24}, - {30, 66128}, - {2, 19}, - {26, 35818}, - {6, 19}, - {35, 59407}, - {6, 19}, - {37, 65328}, - {2, 19}, - {26, 60622}, - {6, 19}, - {11, 60808}, - {8, 43}, - {55, 62027}, - {2, 19}, - {427, 65622}, - {5, 19}, - {35, 59401}, - {6, 19}, - } - for i, want := range wantPlayBounds { - turn := paddingSchedule2612[len(wantDirections)+i] - wantDirection := paddingClientToServer - if i%2 == 1 { - wantDirection = paddingServerToClient - } - if turn.direction != wantDirection { - t.Fatalf("play turn %d direction = %d, want %d", i, turn.direction, wantDirection) - } - if turn.minLength != want[0] || turn.maxLength != want[1] { - t.Fatalf("play turn %d bounds = %d-%d, want %d-%d", i, turn.minLength, turn.maxLength, want[0], want[1]) - } - if len(turn.variants) != 0 { - t.Fatalf("play turn %d unexpectedly has captured variants", i) - } - } - if got := len(paddingSchedule2612[3].variants[0].chunks); got != 30 { - t.Fatalf("registry turn chunks = %d, want 30", got) - } - minimumPlayStart := maxPaddingTurnLength - maximumPlayStart := 0 - for _, variant := range paddingSchedule2612[5].variants { - length := paddingVariantLength(variant) - minimumPlayStart = min(minimumPlayStart, length) - maximumPlayStart = max(maximumPlayStart, length) - if variant.chunks[0] != 4941 { - t.Fatalf("play start first chunk = %d, want 4941", variant.chunks[0]) - } - } - if minimumPlayStart != 6633 || maximumPlayStart != 8790 { - t.Fatalf("play start bounds = %d-%d, want 6633-8790", minimumPlayStart, maximumPlayStart) - } - if err := validatePaddingSchedule(paddingSchedule2612, 2); err != nil { - t.Fatalf("captured schedule is invalid: %v", err) - } - - serverSchedule, err := newServerPaddingSchedule2612() - if err != nil { - t.Fatal(err) - } - if err = validatePaddingSchedule(serverSchedule, 2); err != nil { - t.Fatalf("server schedule is invalid: %v", err) - } - for i, branches := range serverPlayBranches2612 { - turn := serverSchedule[len(startupPaddingSchedule2612)+1+i*2] - got := paddingLengthRange2612{turn.sendMinLength, turn.sendMaxLength} - if got != branches.small && got != branches.large { - t.Fatalf("server play turn %d send range = %v, want %v or %v", i, got, branches.small, branches.large) - } - } - - for range 20 { - clientSchedule, clientErr := newClientPaddingSchedule2612() - if clientErr != nil { - t.Fatal(clientErr) - } - if clientErr = validatePaddingSchedule(clientSchedule, 2); clientErr != nil { - t.Fatalf("client schedule is invalid: %v", clientErr) - } - burstCount := 0 - for _, burst := range clientPlayBursts2612 { - turn := clientSchedule[len(startupPaddingSchedule2612)+burst.playIndex] - got := paddingLengthRange2612{turn.sendMinLength, turn.sendMaxLength} - switch got { - case burst.regular: - case burst.burst: - burstCount++ - default: - t.Fatalf("client play turn %d send range = %v", burst.playIndex, got) - } - } - if burstCount != 1 { - t.Fatalf("client schedule has %d initialization bursts, want 1", burstCount) - } - } - - for variantIndex := range paddingSchedule2612[3].variants { - turn := paddingSchedule2612[3] - turn.sendVariants = []int{variantIndex} - var encoded bytes.Buffer - if err = writePaddingTurnWithSleep(&encoded, turn, 0, func(time.Duration) {}); err != nil { - t.Fatal(err) - } - if err = readPaddingTurn(bytes.NewReader(encoded.Bytes()), paddingSchedule2612[3], 0); err != nil { - t.Fatalf("registry variant %d was rejected: %v", variantIndex, err) - } - } -} - -func TestPaddingVariantPreservesWriteBoundaries(t *testing.T) { - tests := []struct { - name string - turn paddingTurn - prefix int - want []int - }{ - {name: "login acknowledged turn", turn: paddingSchedule2612[0], prefix: 2, want: []int{26, 16}}, - {name: "server response turn", turn: paddingSchedule2612[1], want: []int{26, 21, 25}}, - {name: "single packet turn", turn: paddingSchedule2612[2], want: []int{25}}, - {name: "fixed registry profile", turn: paddingSchedule2612[3], want: paddingSchedule2612[3].variants[0].chunks}, - } - for _, test := range tests { - t.Run(test.name, func(t *testing.T) { - var writer recordingWriter - if err := writePaddingTurnWithSleep(&writer, test.turn, test.prefix, func(time.Duration) {}); err != nil { - t.Fatal(err) - } - if len(writer.writes) != len(test.want) { - t.Fatalf("writes = %v, want %v", writer.writes, test.want) - } - for i := range test.want { - if writer.writes[i] != test.want[i] { - t.Fatalf("writes = %v, want %v", writer.writes, test.want) - } - } - if err := readPaddingTurn(bytes.NewReader(writer.Bytes()), test.turn, test.prefix); err != nil { - t.Fatal(err) - } - }) - } -} - -func TestPaddingVariantAppliesPacing(t *testing.T) { - turn := paddingTurn{ - direction: paddingClientToServer, - startDelay: paddingDelayRange{min: 3 * time.Millisecond, max: 3 * time.Millisecond}, - variants: []paddingVariant{{ - chunks: []int{3, 5, 7}, - delays: []paddingDelayRange{ - {}, - {min: 2 * time.Millisecond, max: 2 * time.Millisecond}, - {min: 4 * time.Millisecond, max: 4 * time.Millisecond}, - }, - }}, - } - var slept []time.Duration - var writer recordingWriter - if err := writePaddingTurnWithSleep(&writer, turn, 3, func(delay time.Duration) { - slept = append(slept, delay) - }); err != nil { - t.Fatal(err) - } - want := []time.Duration{3 * time.Millisecond, 2 * time.Millisecond, 4 * time.Millisecond} - if len(slept) != len(want) { - t.Fatalf("delays = %v, want %v", slept, want) - } - for i := range want { - if slept[i] != want[i] { - t.Fatalf("delays = %v, want %v", slept, want) - } - } -} - -func TestGeneratedPaddingChunksApplyPacing(t *testing.T) { - turn := paddingTurn{ - direction: paddingServerToClient, - minLength: 100, - maxLength: 100, - writeChunkLength: 32, - chunkDelay: paddingDelayRange{min: 2 * time.Millisecond, max: 2 * time.Millisecond}, - } - var slept []time.Duration - var writer recordingWriter - if err := writePaddingTurnWithSleep(&writer, turn, 0, func(delay time.Duration) { - slept = append(slept, delay) - }); err != nil { - t.Fatal(err) - } - wantWrites := []int{32, 32, 32, 4} - if !slicesEqual(writer.writes, wantWrites) { - t.Fatalf("writes = %v, want %v", writer.writes, wantWrites) - } - wantSleeps := []time.Duration{2 * time.Millisecond, 2 * time.Millisecond, 2 * time.Millisecond} - if !slicesEqual(slept, wantSleeps) { - t.Fatalf("delays = %v, want %v", slept, wantSleeps) - } - if err := readPaddingTurn(bytes.NewReader(writer.Bytes()), turn, 0); err != nil { - t.Fatal(err) - } -} - -func TestGeneratedPaddingChunkLengthIsRandomized(t *testing.T) { - turn := paddingTurn{ - direction: paddingServerToClient, - minLength: 100, - maxLength: 100, - writeChunkMinLength: 16, - writeChunkLength: 32, - } - seen := make(map[int]bool) - for range 100 { - var writer recordingWriter - if err := writePaddingTurnWithSleep(&writer, turn, 0, func(time.Duration) {}); err != nil { - t.Fatal(err) - } - firstWrite := writer.writes[0] - if firstWrite < turn.writeChunkMinLength || firstWrite > turn.writeChunkLength { - t.Fatalf("first write = %d", firstWrite) - } - seen[firstWrite] = true - } - if len(seen) < 2 { - t.Fatalf("generated write chunk length did not vary: %v", seen) - } -} - -func TestPaddingDelayRangeIsRandomized(t *testing.T) { - delayRange := millisecondRange(25, 40) - seen := make(map[time.Duration]bool) - for range 100 { - delay, err := randomPaddingDelay(delayRange) - if err != nil { - t.Fatal(err) - } - if delay < delayRange.min || delay > delayRange.max { - t.Fatalf("delay = %s, want %s-%s", delay, delayRange.min, delayRange.max) - } - seen[delay] = true - } - if len(seen) < 2 { - t.Fatalf("padding delay did not vary: %v", seen) - } -} - -func TestPaddingSchedule2612UsesCoarseTimingBands(t *testing.T) { - assertDelayRange(t, "turn 3 to 4", paddingSchedule2612[3].startDelay, 20*time.Millisecond, 50*time.Millisecond) - assertDelayRange(t, "turn 5 to 6", paddingSchedule2612[5].startDelay, 35*time.Millisecond, 50*time.Millisecond) - assertDelayRange(t, "first play client turn", paddingSchedule2612[6].startDelay, time.Millisecond, 30*time.Millisecond) - assertDelayRange(t, "first play server turn", paddingSchedule2612[7].startDelay, time.Millisecond, 45*time.Millisecond) - assertDelayRange(t, "play server chunk pacing", paddingSchedule2612[7].chunkDelay, time.Millisecond, 4*time.Millisecond) - if paddingSchedule2612[6].writeChunkLength != 1024 { - t.Fatalf("play client write chunk = %d, want 1024", paddingSchedule2612[6].writeChunkLength) - } - if paddingSchedule2612[7].writeChunkLength != maxPaddingChunkLength { - t.Fatalf("play server write chunk = %d, want %d", paddingSchedule2612[7].writeChunkLength, maxPaddingChunkLength) - } - if paddingSchedule2612[7].writeChunkMinLength != 32*1024 { - t.Fatalf("play server minimum write chunk = %d, want %d", paddingSchedule2612[7].writeChunkMinLength, 32*1024) - } - - for i, variant := range paddingSchedule2612[3].variants { - minimum, maximum := paddingVariantDelayBounds(variant) - if minimum != 45*time.Millisecond || maximum != 65*time.Millisecond { - t.Fatalf("turn 4 variant %d duration = %s-%s, want 45ms-65ms", i, minimum, maximum) - } - } - for i, variant := range paddingSchedule2612[5].variants { - minimum, maximum := paddingVariantDelayBounds(variant) - if minimum != 10*time.Millisecond || maximum != 25*time.Millisecond { - t.Fatalf("turn 6 variant %d duration = %s-%s, want 10ms-25ms", i, minimum, maximum) - } - } -} - -func assertDelayRange(t *testing.T, name string, got paddingDelayRange, minimum, maximum time.Duration) { - t.Helper() - if got.min != minimum || got.max != maximum { - t.Fatalf("%s delay = %s-%s, want %s-%s", name, got.min, got.max, minimum, maximum) - } -} - -func paddingVariantDelayBounds(variant paddingVariant) (time.Duration, time.Duration) { - var minimum time.Duration - var maximum time.Duration - for _, delay := range variant.delays { - minimum += delay.min - maximum += delay.max - } - return minimum, maximum -} - -func slicesEqual[T comparable](left, right []T) bool { - if len(left) != len(right) { - return false - } - for i := range left { - if left[i] != right[i] { - return false - } - } - return true -} - -func encodePaddingLength(t *testing.T, length int) []byte { - t.Helper() - var encoded bytes.Buffer - value := Varint(length) - if err := value.writeTo(&encoded); err != nil { - t.Fatal(err) - } - return encoded.Bytes() -} - -type oneByteReader struct { - reader io.Reader -} - -func (r *oneByteReader) Read(p []byte) (int, error) { - if len(p) > 1 { - p = p[:1] - } - return r.reader.Read(p) -} - -type recordingWriter struct { - bytes.Buffer - writes []int -} - -func (w *recordingWriter) Write(p []byte) (int, error) { - w.writes = append(w.writes, len(p)) - return w.Buffer.Write(p) -} diff --git a/transport/internet/finalmask/xmc/profile_test.go b/transport/internet/finalmask/xmc/profile_test.go deleted file mode 100644 index 35dd41286..000000000 --- a/transport/internet/finalmask/xmc/profile_test.go +++ /dev/null @@ -1,33 +0,0 @@ -package xmc - -import ( - "bytes" - "testing" -) - -func TestProfilesFromConfigRejectsEmpty(t *testing.T) { - if _, err := profilesFromConfig(nil); err == nil { - t.Fatal("expected empty profiles error") - } -} - -func TestProfilesFromConfig(t *testing.T) { - uuid := bytes.Repeat([]byte{0x2a}, 16) - profiles, err := profilesFromConfig([]*Profile{ - { - Username: "SignedUser", - Uuid: uuid, - TexturesValue: "textures-value", - TexturesSignature: "textures-signature", - }, - }) - if err != nil { - t.Fatalf("build explicit profile: %v", err) - } - if len(profiles) != 1 || profiles[0].Username != "SignedUser" { - t.Fatalf("unexpected profile: %+v", profiles) - } - if profiles[0].TexturesValue != "textures-value" || profiles[0].TexturesSignature != "textures-signature" { - t.Fatalf("textures were not preserved: %+v", profiles[0]) - } -} diff --git a/transport/internet/finalmask/xmc/protocol_test.go b/transport/internet/finalmask/xmc/protocol_test.go deleted file mode 100644 index 3aa68d488..000000000 --- a/transport/internet/finalmask/xmc/protocol_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package xmc - -import ( - "bytes" - "strings" - "testing" -) - -func TestReadPacketDoesNotConsumeFollowingPacket(t *testing.T) { - data := []byte{0x01, 0x80, 0x01, 0x00} - r := bytes.NewReader(data) - if _, err := readPacket(r); err == nil { - t.Fatal("expected truncated packet ID to fail") - } - pkt, err := readPacket(r) - if err != nil { - t.Fatalf("read following packet: %v", err) - } - if pkt.packetID != 0 { - t.Fatalf("packet ID = %d", pkt.packetID) - } -} - -func TestPacketWithLengthReportsWireBytes(t *testing.T) { - var wire bytes.Buffer - written, err := writePacketWithLength(&wire, 0x03) - if err != nil { - t.Fatal(err) - } - if written != 2 || !bytes.Equal(wire.Bytes(), []byte{0x01, 0x03}) { - t.Fatalf("wire = %x, length = %d", wire.Bytes(), written) - } - - packet, read, err := readPacketWithLength(bytes.NewReader(wire.Bytes())) - if err != nil { - t.Fatal(err) - } - if packet.packetID != 0x03 || read != written { - t.Fatalf("packet ID = %d, read = %d, written = %d", packet.packetID, read, written) - } -} - -func TestReadPacketRejectsNonCanonicalLengthVarint(t *testing.T) { - _, _, err := readPacketWithLength(bytes.NewReader([]byte{0x81, 0x00, 0x03})) - if err == nil || !strings.Contains(err.Error(), "non-canonical") { - t.Fatalf("error = %v", err) - } -} - -func TestVarintRejectsOversizedFifthByte(t *testing.T) { - var value Varint - err := value.readFrom(bytes.NewReader([]byte{0xff, 0xff, 0xff, 0xff, 0x1f})) - if err == nil || !strings.Contains(err.Error(), "too large") { - t.Fatalf("error = %v", err) - } -} diff --git a/transport/internet/finalmask/xmc/server.go b/transport/internet/finalmask/xmc/server.go index 43fba9593..6b3b79f49 100644 --- a/transport/internet/finalmask/xmc/server.go +++ b/transport/internet/finalmask/xmc/server.go @@ -328,7 +328,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) (*serverConn, error) { +func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, padding []*Padding) (*serverConn, error) { if len(profiles) == 0 { return nil, fmt.Errorf("empty profiles") } @@ -342,7 +342,7 @@ 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 := newServerPaddingSchedule2612() + paddingSchedule, err := newPaddingSchedule(padding, false) if err != nil { return nil, fmt.Errorf("select padding profile: %w", err) } diff --git a/transport/internet/finalmask/xmc/stream_test.go b/transport/internet/finalmask/xmc/stream_test.go deleted file mode 100644 index bd75d7b86..000000000 --- a/transport/internet/finalmask/xmc/stream_test.go +++ /dev/null @@ -1,81 +0,0 @@ -package xmc - -import ( - "bytes" - "io" - "testing" -) - -type dataAndEOFReader struct { - data []byte -} - -func (r *dataAndEOFReader) Read(p []byte) (int, error) { - if len(r.data) == 0 { - return 0, io.EOF - } - n := copy(p, r.data) - r.data = r.data[n:] - return n, io.EOF -} - -type shortWriter struct { - bytes.Buffer -} - -func (w *shortWriter) Write(p []byte) (int, error) { - if len(p) > 1 { - p = p[:len(p)/2] - } - return w.Buffer.Write(p) -} - -func TestCryptoReaderPreservesDataReturnedWithEOF(t *testing.T) { - secret := []byte("0123456789abcdef") - plaintext := []byte("payload returned with EOF") - var encrypted bytes.Buffer - writer, err := newCryptoWriter(&encrypted, secret) - if err != nil { - t.Fatal(err) - } - if _, err = writer.Write(plaintext); err != nil { - t.Fatal(err) - } - - reader, err := newCryptoReader(&dataAndEOFReader{data: encrypted.Bytes()}, secret) - if err != nil { - t.Fatal(err) - } - got := make([]byte, len(plaintext)) - n, err := reader.Read(got) - if err == nil || n != len(plaintext) { - t.Fatalf("Read = %d, %v", n, err) - } - if !bytes.Equal(got[:n], plaintext) { - t.Fatalf("plaintext = %q", got[:n]) - } -} - -func TestCryptoWriterHandlesShortWrites(t *testing.T) { - secret := []byte("0123456789abcdef") - plaintext := bytes.Repeat([]byte("short-write"), 100) - var dst shortWriter - writer, err := newCryptoWriter(&dst, secret) - if err != nil { - t.Fatal(err) - } - if n, err := writer.Write(plaintext); err != nil || n != len(plaintext) { - t.Fatalf("Write = %d, %v", n, err) - } - reader, err := newCryptoReader(bytes.NewReader(dst.Bytes()), secret) - if err != nil { - t.Fatal(err) - } - got, err := io.ReadAll(reader) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(got, plaintext) { - t.Fatal("decrypted payload mismatch") - } -}