From 919d0ae8eb54b1f4728ce68bef629840b570bb6b Mon Sep 17 00:00:00 2001 From: yangdujun <137720155+yandujun363@users.noreply.github.com> Date: Mon, 30 Nov 2026 23:53:09 +0800 Subject: [PATCH] XMC finalmask: Vanilla 26.3 login from a version table; 20 Hz data shaping; Fix two crypto issues (breaking) (#7456) https://github.com/XTLS/Xray-core/issues/7455#issuecomment-7130696217 https://github.com/XTLS/Xray-core/issues/7455#issuecomment-7143329154 https://github.com/XTLS/Xray-core/issues/7455#issuecomment-7226532810 Closes https://github.com/XTLS/Xray-core/issues/7455#issuecomment-7132961284 Fixes https://github.com/XTLS/Xray-core/issues/7455#issuecomment-7240081698 Fixes https://github.com/XTLS/Xray-core/pull/7456#issuecomment-7246916366 --- infra/conf/transport_finalmask.go | 27 +- infra/conf/transport_finalmask_xmc_test.go | 90 +++ transport/internet/finalmask/xmc/channels.go | 77 +++ .../internet/finalmask/xmc/channels_test.go | 188 +++++ transport/internet/finalmask/xmc/client.go | 356 +++++++--- transport/internet/finalmask/xmc/config.go | 61 +- transport/internet/finalmask/xmc/config.pb.go | 49 +- transport/internet/finalmask/xmc/config.proto | 15 + .../internet/finalmask/xmc/config_test.go | 6 +- .../internet/finalmask/xmc/derivation.go | 12 +- .../internet/finalmask/xmc/derivation_test.go | 241 +++++++ .../finalmask/xmc/handshake_oracle_test.go | 647 ++++++++++++++++++ .../finalmask/xmc/handshake_secret.go | 91 +++ .../internet/finalmask/xmc/handshake_test.go | 22 +- .../internet/finalmask/xmc/login_flow_test.go | 308 +++++++++ .../internet/finalmask/xmc/packet_stream.go | 280 ++++++-- transport/internet/finalmask/xmc/padding.go | 173 +++-- .../finalmask/xmc/padding_frames_test.go | 40 +- .../internet/finalmask/xmc/padding_reader.go | 8 +- .../finalmask/xmc/padding_reader_test.go | 14 +- transport/internet/finalmask/xmc/profile.go | 27 +- transport/internet/finalmask/xmc/protocol.go | 27 +- .../internet/finalmask/xmc/protocol_probe.go | 154 +++++ .../finalmask/xmc/protocol_probe_test.go | 251 +++++++ .../internet/finalmask/xmc/protocol_table.go | 210 ++++++ .../finalmask/xmc/protocol_table_test.go | 165 +++++ transport/internet/finalmask/xmc/server.go | 446 +++++++----- transport/internet/finalmask/xmc/stream.go | 29 +- .../finalmask/xmc/tick_stream_test.go | 209 ++++++ transport/internet/finalmask/xmc/yggdrasil.go | 8 + .../internet/finalmask/xmc/yggdrasil_test.go | 161 ++++- 31 files changed, 3924 insertions(+), 468 deletions(-) create mode 100644 transport/internet/finalmask/xmc/channels.go create mode 100644 transport/internet/finalmask/xmc/channels_test.go create mode 100644 transport/internet/finalmask/xmc/derivation_test.go create mode 100644 transport/internet/finalmask/xmc/handshake_oracle_test.go create mode 100644 transport/internet/finalmask/xmc/handshake_secret.go create mode 100644 transport/internet/finalmask/xmc/login_flow_test.go create mode 100644 transport/internet/finalmask/xmc/protocol_probe.go create mode 100644 transport/internet/finalmask/xmc/protocol_probe_test.go create mode 100644 transport/internet/finalmask/xmc/protocol_table.go create mode 100644 transport/internet/finalmask/xmc/protocol_table_test.go create mode 100644 transport/internet/finalmask/xmc/tick_stream_test.go diff --git a/infra/conf/transport_finalmask.go b/infra/conf/transport_finalmask.go index d10159562..5db631771 100644 --- a/infra/conf/transport_finalmask.go +++ b/infra/conf/transport_finalmask.go @@ -975,6 +975,17 @@ type XMC struct { // NoPadding disables padding. An explicit empty "paddings" array means the // same; an absent one keeps the built-in preset. NoPadding bool `json:"noPadding,omitempty"` + // Custom payload channels that carry the tunnel byte stream and the startup + // padding. Both ends must use the same pair; empty keeps the defaults + // (xmc:data / xmc:pad). Vanilla's "minecraft" namespace is rejected. + DataChannel string `json:"dataChannel,omitempty"` + PaddingChannel string `json:"paddingChannel,omitempty"` + // Minecraft network protocol number the client advertises, for example 777 + // for 26.3. Zero detects it from the peer's status response (cached per + // destination) and falls back to the newest version the mask knows. Set it to + // skip detection or to pin a version; the server follows whatever the client + // names. + ProtocolVersion uint32 `json:"protocolVersion,omitempty"` } type XMCPaddingTurn struct { @@ -1040,7 +1051,21 @@ func (c *XMC) Build() (proto.Message, error) { if noPadding && len(c.Paddings) > 0 { return nil, fmt.Errorf("minecraft padding: noPadding and paddings are exclusive") } - config := &xmc.Config{Hostname: c.Hostname, NoPadding: noPadding} + if err := xmc.ValidateProtocolVersion(c.ProtocolVersion); err != nil { + return nil, fmt.Errorf("minecraft protocolVersion: %w", err) + } + config := &xmc.Config{ + Hostname: c.Hostname, + NoPadding: noPadding, + DataChannel: c.DataChannel, + PaddingChannel: c.PaddingChannel, + ProtocolVersion: c.ProtocolVersion, + } + dataChannel, paddingChannel, channelErr := config.ChannelIDs() + if channelErr != nil { + return nil, fmt.Errorf("minecraft channels: %w", channelErr) + } + config.DataChannel, config.PaddingChannel = dataChannel, paddingChannel for i, turn := range c.Paddings { minimum, maximum, err := ParseRangeString(turn.Length) if err != nil { diff --git a/infra/conf/transport_finalmask_xmc_test.go b/infra/conf/transport_finalmask_xmc_test.go index 4b7d7b22d..68a4cb07b 100644 --- a/infra/conf/transport_finalmask_xmc_test.go +++ b/infra/conf/transport_finalmask_xmc_test.go @@ -242,3 +242,93 @@ func TestXMCBuildDisablesPadding(t *testing.T) { t.Fatalf("expected an exclusive padding error, got %v", err) } } + +func xmcTestProfiles() []XMCProfile { + return []XMCProfile{{ + Username: "TestUser", + UUID: "00112233-4455-6677-8899-aabbccddeeff", + TexturesValue: "textures-value", + TexturesSignature: "textures-signature", + }} +} + +func TestXMCBuildChannels(t *testing.T) { + built, err := (&XMC{ + Password: "test-password", + Profiles: xmcTestProfiles(), + DataChannel: "myxmc:stream", + PaddingChannel: "myxmc:noise", + }).Build() + if err != nil { + t.Fatalf("build XMC config: %v", err) + } + config := built.(*xmc.Config) + if config.DataChannel != "myxmc:stream" || config.PaddingChannel != "myxmc:noise" { + t.Fatalf("channels = %q, %q", config.DataChannel, config.PaddingChannel) + } +} + +func TestXMCBuildChannelDefaults(t *testing.T) { + built, err := (&XMC{Password: "test-password", Profiles: xmcTestProfiles()}).Build() + if err != nil { + t.Fatalf("build XMC config: %v", err) + } + config := built.(*xmc.Config) + if config.DataChannel != xmc.DefaultDataChannel || config.PaddingChannel != xmc.DefaultPaddingChannel { + t.Fatalf("default channels = %q, %q", config.DataChannel, config.PaddingChannel) + } +} + +func TestXMCBuildRejectsChannels(t *testing.T) { + cases := map[string]struct { + data string + padding string + }{ + "vanilla_namespace": {"minecraft:data", ""}, + "no_colon": {"xmcdata", ""}, + "empty_path": {"xmc:", ""}, + "uppercase": {"Xmc:data", ""}, + "same_channel": {"xmc:same", "xmc:same"}, + "too_long": {strings.Repeat("a", 129) + ":b", ""}, + } + for name, test := range cases { + _, err := (&XMC{ + Password: "test-password", + Profiles: xmcTestProfiles(), + DataChannel: test.data, + PaddingChannel: test.padding, + }).Build() + if err == nil || !strings.Contains(err.Error(), "channel") { + t.Fatalf("%s: expected a channel error, got %v", name, err) + } + } +} + +func TestXMCBuildProtocolVersion(t *testing.T) { + profile := XMCProfile{ + Username: "TestUser", + UUID: "00112233-4455-6677-8899-aabbccddeeff", + TexturesValue: "textures-value", + TexturesSignature: "textures-signature", + } + + built, err := (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}}).Build() + if err != nil { + t.Fatalf("build default XMC config: %v", err) + } + if got := built.(*xmc.Config).ProtocolVersion; got != 0 { + t.Fatalf("default protocol version = %d, want 0 (newest)", got) + } + + built, err = (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}, ProtocolVersion: 775}).Build() + if err != nil { + t.Fatalf("build XMC config with a protocol version: %v", err) + } + if got := built.(*xmc.Config).ProtocolVersion; got != 775 { + t.Fatalf("protocol version = %d, want 775", got) + } + + if _, err = (&XMC{Password: "test-password", Profiles: []XMCProfile{profile}, ProtocolVersion: 778}).Build(); err == nil || !strings.Contains(err.Error(), "unsupported protocol version 778") { + t.Fatalf("expected an unknown protocol version to be rejected, got %v", err) + } +} diff --git a/transport/internet/finalmask/xmc/channels.go b/transport/internet/finalmask/xmc/channels.go new file mode 100644 index 000000000..ca9fb20c3 --- /dev/null +++ b/transport/internet/finalmask/xmc/channels.go @@ -0,0 +1,77 @@ +package xmc + +import ( + "fmt" + "regexp" + "strings" +) + +const ( + // DefaultDataChannel carries the tunnel byte stream and DefaultPaddingChannel + // carries the startup padding. Both ends must agree on the pair, and the + // defaults are public constants, so a deployment that wants a different + // fingerprint renames them on both sides. + DefaultDataChannel = "xmc:data" + DefaultPaddingChannel = "xmc:pad" + + // MaxChannelIDLength bounds a channel id. The id travels in every custom + // payload header, so a long one is pure overhead; vanilla itself has no + // limit beyond the string encoding. + MaxChannelIDLength = 128 +) + +var ( + channelNamespacePattern = regexp.MustCompile(`^[a-z0-9_.-]+$`) + channelPathPattern = regexp.MustCompile(`^[a-z0-9/._-]+$`) +) + +// ChannelIDs returns the two configured custom payload channels, filling in the +// defaults for empty fields. Both are validated because both ends have to +// register them as Minecraft resource locations. +func (c *Config) ChannelIDs() (dataChannel, paddingChannel string, err error) { + dataChannel = c.DataChannel + if dataChannel == "" { + dataChannel = DefaultDataChannel + } + paddingChannel = c.PaddingChannel + if paddingChannel == "" { + paddingChannel = DefaultPaddingChannel + } + if err = ValidateChannelID(dataChannel); err != nil { + return "", "", fmt.Errorf("data channel: %w", err) + } + if err = ValidateChannelID(paddingChannel); err != nil { + return "", "", fmt.Errorf("padding channel: %w", err) + } + if dataChannel == paddingChannel { + return "", "", fmt.Errorf("data and padding channels must differ: %q", dataChannel) + } + return dataChannel, paddingChannel, nil +} + +// ValidateChannelID checks one custom payload id as a Minecraft resource +// location: namespace:path with vanilla's character rules. The "minecraft" +// namespace is reserved, because every vanilla custom payload id lives there and +// reusing one would make the tunnel collide with the game. +func ValidateChannelID(id string) error { + if id == "" { + return fmt.Errorf("empty channel id") + } + if len(id) > MaxChannelIDLength { + return fmt.Errorf("channel id %q is longer than %d bytes", id, MaxChannelIDLength) + } + namespace, path, found := strings.Cut(id, ":") + if !found || strings.Contains(path, ":") { + return fmt.Errorf("channel id %q is not namespace:path", id) + } + if namespace == "" || namespace == ".." || !channelNamespacePattern.MatchString(namespace) { + return fmt.Errorf("channel id %q has an invalid namespace: only a-z, 0-9, '_', '.' and '-' are allowed, and it cannot be \"..\"", id) + } + if namespace == "minecraft" { + return fmt.Errorf("channel id %q uses the vanilla \"minecraft\" namespace; vanilla custom payload ids belong to the game", id) + } + if path == "" || !channelPathPattern.MatchString(path) { + return fmt.Errorf("channel id %q has an invalid path: only a-z, 0-9, '_', '-', '.' and '/' are allowed", id) + } + return nil +} diff --git a/transport/internet/finalmask/xmc/channels_test.go b/transport/internet/finalmask/xmc/channels_test.go new file mode 100644 index 000000000..10d31028c --- /dev/null +++ b/transport/internet/finalmask/xmc/channels_test.go @@ -0,0 +1,188 @@ +package xmc + +import ( + "bytes" + "strings" + "testing" + "time" +) + +func TestChannelIDsDefaults(t *testing.T) { + dataChannel, paddingChannel, err := (&Config{}).ChannelIDs() + if err != nil { + t.Fatalf("default channels: %v", err) + } + if dataChannel != DefaultDataChannel || paddingChannel != DefaultPaddingChannel { + t.Fatalf("defaults = %q, %q", dataChannel, paddingChannel) + } +} + +func TestChannelIDsConfigured(t *testing.T) { + config := &Config{DataChannel: "myxmc:stream", PaddingChannel: "myxmc:noise"} + dataChannel, paddingChannel, err := config.ChannelIDs() + if err != nil { + t.Fatalf("configured channels: %v", err) + } + if dataChannel != "myxmc:stream" || paddingChannel != "myxmc:noise" { + t.Fatalf("channels = %q, %q", dataChannel, paddingChannel) + } +} + +func TestChannelIDsRejectEqualChannels(t *testing.T) { + config := &Config{DataChannel: "myxmc:same", PaddingChannel: "myxmc:same"} + if _, _, err := config.ChannelIDs(); err == nil { + t.Fatal("expected an error for one channel used twice") + } +} + +func TestValidateChannelID(t *testing.T) { + tests := []struct { + id string + ok bool + }{ + {"xmc:data", true}, + {"a:b", true}, + {"my-xmc:v1/main.data", true}, + {strings.Repeat("a", 126) + ":b", true}, // exactly 128 bytes + {"", false}, + {"xmcdata", false}, + {"xmc:data:extra", false}, + {":data", false}, + {"xmc:", false}, + {"Xmc:data", false}, + {"xmc:Data", false}, + {"..:data", false}, + {"xmc:data space", false}, + {"xmc:data!", false}, + {"minecraft:data", false}, + {"minecraft:brand", false}, + {strings.Repeat("a", 127) + ":b", false}, // 129 bytes + } + for _, test := range tests { + err := ValidateChannelID(test.id) + if test.ok && err != nil { + t.Fatalf("%q: unexpected error %v", test.id, err) + } + if !test.ok && err == nil { + t.Fatalf("%q: expected an error", test.id) + } + } +} + +// TestPaddingFramingDependsOnChannelLength pins that the exact frame lengths of +// a captured preset follow the configured channel name instead of the default. +func TestPaddingFramingDependsOnChannelLength(t *testing.T) { + const channel = "my-long-namespace:padding-channel" + framing := newPaddingFraming(channel) + if got, want := framing.overhead(), defaultPaddingFraming.overhead()+len(channel)-len(DefaultPaddingChannel); got != want { + t.Fatalf("overhead = %d, want %d", got, want) + } + for _, length := range []int{1024, 48 * 1024, 1024 * 1024} { + plan, err := framing.plan(length) + if err != nil { + t.Fatalf("plan %d: %v", length, err) + } + total := 0 + for _, frameLength := range plan { + if _, ok := framing.frameDataLength(frameLength); !ok { + t.Fatalf("plan %d contains unreachable frame %d", length, frameLength) + } + total += frameLength + } + if total != length { + t.Fatalf("plan %d totals %d", length, total) + } + } +} + +// TestPaddingChannelIsConfigurable checks that the startup-padding reader drains +// exactly the configured channel and leaves every other payload alone. +func TestPaddingChannelIsConfigurable(t *testing.T) { + const paddingChannel = "myxmc:noise" + packetID := paddingFramePacketID(configurationPacketIDs121, false) + + build := func() []byte { + var wire bytes.Buffer + channel := String(paddingChannel) + padding := RestBytes(make([]byte, 64)) + if err := writePacket(&wire, packetID, &channel, &padding); err != nil { + t.Fatal(err) + } + following := String(DefaultDataChannel) + payload := RestBytes("tunnel bytes") + if err := writePacket(&wire, packetID, &following, &payload); err != nil { + t.Fatal(err) + } + return wire.Bytes() + } + + channelOf := func(frame []byte) string { + t.Helper() + packet, err := readPacket(bytes.NewReader(frame)) + if err != nil { + t.Fatal(err) + } + var channel String + if err := channel.readFrom(bytes.NewReader(packet.data)); err != nil { + t.Fatal(err) + } + return string(channel) + } + + frame, err := readPastPadding(bytes.NewReader(build()), packetID, paddingChannel) + if err != nil { + t.Fatalf("readPastPadding: %v", err) + } + if got := channelOf(frame); got != DefaultDataChannel { + t.Fatalf("drained past the configured padding channel, got %q", got) + } + + // A different configured name must not silently drop the frame. + frame, err = readPastPadding(bytes.NewReader(build()), packetID, "other:pad") + if err != nil { + t.Fatalf("readPastPadding with another channel: %v", err) + } + if got := channelOf(frame); got != paddingChannel { + t.Fatalf("expected the unrecognized frame back, got %q", got) + } +} + +// TestTickStreamUsesConfiguredChannels checks that a configured pair reaches the +// wire: data payloads on the data channel, idle ticks on the padding channel. +func TestTickStreamUsesConfiguredChannels(t *testing.T) { + const ( + dataChannel = "myxmc:stream" + paddingChannel = "myxmc:noise" + ) + writer := &tickTestWriter{} + stream := newTickStream(nil, writer, true, configurationPacketIDs121, dataChannel, paddingChannel) + defer stream.Stop() + + if _, err := stream.Write([]byte("hello")); err != nil { + t.Fatal(err) + } + time.Sleep(120 * time.Millisecond) + stream.Stop() + _ = stream.Flush() + + seenData, seenPadding := false, false + for _, batch := range writer.snapshot() { + for _, packet := range readTickBatch(t, batch) { + channel, payload := tickPacketChannelAndPayload(t, packet) + switch channel { + case dataChannel: + seenData = true + if !bytes.Equal(payload, []byte("hello")) { + t.Fatalf("data payload = %q", payload) + } + case paddingChannel: + seenPadding = true + default: + t.Fatalf("unexpected channel %q", channel) + } + } + } + if !seenData || !seenPadding { + t.Fatalf("configured channels not used: data=%v padding=%v", seenData, seenPadding) + } +} diff --git a/transport/internet/finalmask/xmc/client.go b/transport/internet/finalmask/xmc/client.go index 34414ca4a..c1fcffb03 100644 --- a/transport/internet/finalmask/xmc/client.go +++ b/transport/internet/finalmask/xmc/client.go @@ -23,6 +23,11 @@ type clientConn struct { state clientState + // protocol selects the packet ids and field shapes of the login the client + // performs. The server picks its own row from the handshake, so both ends + // agree without a negotiation round trip. + protocol protocolVersion + handshakeLock sync.Mutex lifecycleMu sync.Mutex closed bool @@ -30,9 +35,11 @@ type clientConn struct { password string rsaPublicKey []byte hostname string + dataChannel string + paddingChannel string yggdrasil *yggdrasilAuth paddingSchedule []paddingTurn - packet *packetStream + packet *tickStream deadlines *connectionDeadlines done chan struct{} @@ -46,7 +53,7 @@ var ( clientStateProxy clientState = 2 ) -func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth) (*clientConn, error) { +func newClientConn(c net.Conn, protocol protocolVersion, profiles []loginProfile, password string, rsaPublicKey []byte, hostname string, paddingSchedule []paddingTurn, yggdrasil *yggdrasilAuth, dataChannel, paddingChannel string) (*clientConn, error) { if len(rsaPublicKey) == 0 && yggdrasil == nil { return nil, fmt.Errorf("empty rsa public key") } @@ -61,11 +68,14 @@ func newClientConn(c net.Conn, profiles []loginProfile, password string, rsaPubl writer: c, c: c, state: clientStateHandshake, + protocol: protocol, handshakeLock: sync.Mutex{}, profiles: profiles, password: password, rsaPublicKey: rsaPublicKey, hostname: hostname, + dataChannel: dataChannel, + paddingChannel: paddingChannel, yggdrasil: yggdrasil, paddingSchedule: paddingSchedule, deadlines: newConnectionDeadlines(c), @@ -92,10 +102,10 @@ func (c *clientConn) handshake() error { defer func() { _ = c.deadlines.endHandshake() }() var ( - protocolVersion Varint = Varint(775) - serverAddress String = String(c.hostname) - serverPort UnsignedShort = UnsignedShort(25565) - nextState Varint = Varint(2) + protocolNumber Varint = c.protocol.number + serverAddress String = String(c.hostname) + serverPort UnsignedShort = UnsignedShort(25565) + nextState Varint = Varint(2) ) host, portString, err := net.SplitHostPort(c.c.RemoteAddr().String()) @@ -110,11 +120,37 @@ func (c *clientConn) handshake() error { } } - err = writePacket(c.writer, 0x00, &protocolVersion, &serverAddress, &serverPort, &nextState) + err = writePacket(c.writer, handshakeServerboundIntention, &protocolNumber, &serverAddress, &serverPort, &nextState) if err != nil { return fmt.Errorf("write handshake packet: %w", err) } + // The session server keeps a single server id per profile: only the last + // /join answers hasJoined. One account is therefore one login at a time, so + // the whole exchange is serialized per account until the server has verified + // the player and answered with Login Finished. Releasing the lock after + // /join alone is not enough: a second login would overwrite the session + // while the first server is still polling hasJoined, and that server would + // disconnect with unverified_username. + // + // The lock is released as soon as the login is verified, before the startup + // padding (which takes time on purpose) so a queue of connections still + // logs in at the API's pace rather than at the peer's padding pace. A peer + // that never answers holds this account's logins until the handshake + // deadline, which is the same wait its own connection would have. + releaseLogin := func() {} + if c.yggdrasil != nil { + c.yggdrasil.loginMu.Lock() + released := false + releaseLogin = func() { + if !released { + released = true + c.yggdrasil.loginMu.Unlock() + } + } + defer releaseLogin() + } + // Login Start var selectedProfile loginProfile if c.yggdrasil != nil { @@ -139,57 +175,156 @@ func (c *clientConn) handshake() error { } username := String(selectedProfile.Username) - err = writePacket(c.writer, 0x00, &username, &selectedProfile.UUID) + err = writePacket(c.writer, c.protocol.login.serverboundLoginStart, &username, &selectedProfile.UUID) if err != nil { return fmt.Errorf("write login start: %w", err) } - // Encryption Request - pkt, err := readPacket(c.reader) - if err != nil { - return fmt.Errorf("read encryption request: %w", err) - } + // From here the server drives the login: Encryption Request, then optionally + // Set Compression, then Login Finished; queries and cookie requests can + // appear at any point between them, so the client loops over the login + // packets like a vanilla one instead of expecting a fixed sequence. + // + // The encryption exchange is mandatory. XMC exists to look like a licensed + // player joining an online-mode server (with a third-party API in Yggdrasil + // mode), and an offline-mode login skips the encryption request entirely, so + // there is nothing to reproduce and nothing to authenticate. + handledEncryption := false + joinedSession := false + for { + pkt, readErr := readPacket(c.reader) + if readErr != nil { + return fmt.Errorf("read login packet: %w", readErr) + } - if pkt.packetID != 0x01 { - return fmt.Errorf("bad encrypt request packet id") - } + switch pkt.packetID { + case c.protocol.login.clientboundHello: + if handledEncryption { + return fmt.Errorf("duplicate encryption request") + } + handledEncryption = true + updatedProfile, joined, helloErr := c.handleEncryptionRequest(pkt, selectedProfile) + if helloErr != nil { + return helloErr + } + selectedProfile = updatedProfile + joinedSession = joined + case c.protocol.login.clientboundLoginCompression: + // Set Compression is not compressed itself and must be handled before + // the packet that follows it, which already uses the compressed + // framing. The threshold only decides whether the framing applies: + // this writer never compresses, so a server-side threshold does not + // shrink padding turns. + var threshold Varint + if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil { + return fmt.Errorf("read login compression threshold: %w", thresholdErr) + } + if threshold >= 0 { + c.reader = newCompressionReader(c.reader) + c.writer = newCompressionWriter(c.writer) + } + + case c.protocol.login.clientboundCustomQuery: + // A vanilla 26.x client answers a login query with a null payload: the + // server-driven login extensions of older versions are gone, and a + // server that still asks gets an explicit "no answer". + if answerErr := c.answerCustomQuery(pkt); answerErr != nil { + return answerErr + } + + case c.protocol.login.clientboundCookieRequest: + if answerErr := c.answerCookieRequest(pkt); answerErr != nil { + return answerErr + } + + case c.protocol.login.clientboundLoginDisconnect: + var reason String + if readErr := pkt.readFields(&reason); readErr != nil { + return fmt.Errorf("authentication rejected") + } + if isProtocolVersionReject(string(reason)) { + forgetProbedVersions() + } + return fmt.Errorf("authentication rejected: %s", reason) + + case c.protocol.login.clientboundLoginFinished: + if !handledEncryption { + return fmt.Errorf("server finished the login without an encryption request: offline-mode servers are not supported") + } + receivedProfile, finishErr := c.readLoginFinished(pkt) + if finishErr != nil { + return fmt.Errorf("read login finished fields: %w", finishErr) + } + // Login Finished is written only after the server's hasJoined + // succeeded, so the session is verified and the next login for this + // account may join. + releaseLogin() + if verifyErr := c.verifyLoginProfile(receivedProfile, selectedProfile, joinedSession); verifyErr != nil { + return verifyErr + } + selectedProfile = receivedProfile + + loginAcknowledgedLength, writeErr := writePacketWithLength(c.writer, c.protocol.login.serverboundLoginAcknowledged) + if writeErr != nil { + return fmt.Errorf("write login acknowledged: %w", writeErr) + } + return c.startProxy(loginAcknowledgedLength) + + default: + return fmt.Errorf("unexpected login packet: 0x%02x", pkt.packetID) + } + } +} + +// handleEncryptionRequest performs the shared-secret exchange and reports the +// session profile plus whether the session server was joined, which decides how +// strictly the returned game profile can be checked. +func (c *clientConn) handleEncryptionRequest(pkt *mcPacket, profile loginProfile) (loginProfile, bool, error) { var ( - serverId String - publicKey Bytes - verifyToken Bytes + serverId String + publicKey Bytes + verifyToken Bytes + shouldAuthenticate Boolean ) - err = pkt.readFields(&serverId, &publicKey, &verifyToken) + err := pkt.readFields(&serverId, &publicKey, &verifyToken, &shouldAuthenticate) if err != nil { - return fmt.Errorf("read encryption request fields: %w", err) + return profile, false, fmt.Errorf("read encryption request fields: %w", err) + } + + // shouldAuthenticate is false for an offline-mode server that still encrypts. + // XMC only reproduces the online-mode login, so the client does not pretend + // to authenticate against it. + if c.yggdrasil != nil && !shouldAuthenticate { + return profile, false, fmt.Errorf("server asked the client not to authenticate: offline-mode servers are not supported") } if c.yggdrasil == nil && !bytes.Equal(publicKey, c.rsaPublicKey) { - return fmt.Errorf("server public key mismatch") + return profile, false, fmt.Errorf("server public key mismatch") } k, err := x509.ParsePKIXPublicKey(publicKey) if err != nil { - return fmt.Errorf("parse server public key: %w", err) + return profile, false, fmt.Errorf("parse server public key: %w", err) } rsaPublicKey, ok := k.(*rsa.PublicKey) if !ok { - return fmt.Errorf("parse server public key: not rsa") + return profile, false, fmt.Errorf("parse server public key: not rsa") } if rsaPublicKey.N.BitLen() < 1024 { - return fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen()) + return profile, false, fmt.Errorf("server public key is too short: %d bits", rsaPublicKey.N.BitLen()) } sharedSecret := make([]byte, 16) if _, err = rand.Read(sharedSecret); err != nil { - return fmt.Errorf("generate shared secret: %w", err) + return profile, false, fmt.Errorf("generate shared secret: %w", err) } encryptedSharedSecret, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, sharedSecret) if err != nil { - return fmt.Errorf("encrypt shared secret: %w", err) + return profile, false, fmt.Errorf("encrypt shared secret: %w", err) } if c.yggdrasil == nil { @@ -198,107 +333,132 @@ func (c *clientConn) handshake() error { encryptedVerifyToken, err := rsa.EncryptPKCS1v15(rand.Reader, rsaPublicKey, verifyToken) if err != nil { - return fmt.Errorf("encrypt verify token: %w", err) + return profile, false, fmt.Errorf("encrypt verify token: %w", err) } - // Send Encryption Response + // Send Encryption Response, then switch the ciphers on: vanilla starts + // encrypting only after the response itself has been written. err = writePacket( c.writer, - 0x01, + c.protocol.login.serverboundKey, (*Bytes)(&encryptedSharedSecret), (*Bytes)(&encryptedVerifyToken), ) if err != nil { - return fmt.Errorf("write encryption response: %w", err) + return profile, false, fmt.Errorf("write encryption response: %w", err) } - // Enable encryption c.reader, err = newCryptoReader(c.reader, sharedSecret) if err != nil { - return fmt.Errorf("new crypto reader: %w", err) + return profile, false, fmt.Errorf("new crypto reader: %w", err) } c.writer, err = newCryptoWriter(c.writer, sharedSecret) if err != nil { - return fmt.Errorf("new crypto writer: %w", err) + return profile, false, fmt.Errorf("new crypto writer: %w", err) } - if c.yggdrasil != nil { - // Standard online-mode login: join the session with the hash of the - // handshake data, the server verifies it through hasJoined. - serverID := minecraftServerID(string(serverId), sharedSecret, publicKey) - token, joinErr := c.yggdrasil.join(context.Background(), serverID) - if joinErr != nil { - return fmt.Errorf("yggdrasil session join: %w", joinErr) - } - profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID) - if uuidErr != nil { - return fmt.Errorf("yggdrasil session join: %w", uuidErr) - } - selectedProfile = loginProfile{ - Username: token.profile.Name, - UUID: profileUUID, - } + // Online mode: join the session with the digest of the handshake data so the + // server can verify it through hasJoined. The password mode has no session + // server; its login is authenticated by the pre-shared password instead. + if c.yggdrasil == nil { + return profile, false, nil } - pkt, err = readPacket(c.reader) - if err != nil { - return fmt.Errorf("read login finished: %w", err) + serverID := minecraftServerID(string(serverId), sharedSecret, publicKey) + token, joinErr := c.yggdrasil.join(context.Background(), serverID) + if joinErr != nil { + return profile, false, fmt.Errorf("yggdrasil session join: %w", joinErr) } - // Set Compression is not compressed itself and must be handled before the - // packet that follows it, which already uses the compressed framing. The - // threshold only decides whether the framing applies: this writer never - // compresses, so a server-side threshold does not shrink padding turns. - if pkt.packetID == 0x03 { - var threshold Varint - if thresholdErr := pkt.readFields(&threshold); thresholdErr != nil { - return fmt.Errorf("read login compression threshold: %w", thresholdErr) - } - if threshold >= 0 { - c.reader = newCompressionReader(c.reader) - c.writer = newCompressionWriter(c.writer) - } - pkt, err = readPacket(c.reader) - if err != nil { - return fmt.Errorf("read login finished: %w", err) - } - } - if pkt.packetID == 0x00 { - var reason String - if readErr := pkt.readFields(&reason); readErr != nil { - return fmt.Errorf("authentication rejected") - } - return fmt.Errorf("authentication rejected: %s", reason) - } - if pkt.packetID != 0x02 { - return fmt.Errorf("bad login finished packet id: %d", pkt.packetID) + profileUUID, uuidErr := normalizeMinecraftUUID(token.profile.ID) + if uuidErr != nil { + return profile, false, fmt.Errorf("yggdrasil session join: %w", uuidErr) } + return loginProfile{Username: token.profile.Name, UUID: profileUUID}, true, nil +} - receivedProfile, err := readLoginSuccess(pkt) - if err != nil { - return fmt.Errorf("read login finished fields: %w", err) +// answerCustomQuery replies to a login query with a null payload, which is what +// a vanilla 26.x client sends. +func (c *clientConn) answerCustomQuery(pkt *mcPacket) error { + var transactionID Varint + if err := pkt.readFields(&transactionID); err != nil { + return fmt.Errorf("read login query: %w", err) } - if c.yggdrasil != nil { - if !sameProfileIdentity(receivedProfile, selectedProfile) { + // The answer payload is nullable; a vanilla 26.x client leaves it absent. + answered := Boolean(false) + if err := writePacket(c.writer, c.protocol.login.serverboundCustomQueryAnswer, &transactionID, &answered); err != nil { + return fmt.Errorf("write login query answer: %w", err) + } + return nil +} + +// answerCookieRequest replies with an absent cookie, like a client that has +// never received a cookie for the key. +func (c *clientConn) answerCookieRequest(pkt *mcPacket) error { + var key String + if err := pkt.readFields(&key); err != nil { + return fmt.Errorf("read login cookie request: %w", err) + } + // The cookie is nullable; an absent value means "no cookie for this key". + answered := Boolean(false) + if err := writePacket(c.writer, c.protocol.login.serverboundCookieResponse, &key, &answered); err != nil { + return fmt.Errorf("write login cookie response: %w", err) + } + return nil +} + +// readLoginFinished reads the game profile and, from 26.2 on, the connection +// session id that follows it. Trailing bytes are ignored on purpose: Mojang has +// appended a field to this packet before, and a client that needs an exact +// length would stop pairing on the next release. +func (c *clientConn) readLoginFinished(pkt *mcPacket) (loginProfile, error) { + var ( + profile loginProfile + username String + ) + fields := []field{&profile.UUID, &username, &profile.Properties} + if c.protocol.loginFinishedSessionID { + var sessionID UUID + fields = append(fields, &sessionID) + } + if err := pkt.readFields(fields...); err != nil { + return loginProfile{}, err + } + profile.Username = string(username) + return profile, nil +} + +// verifyLoginProfile checks the profile the server returned. A session join +// pins the identity to the Yggdrasil account and its signed textures; the +// pre-shared password mode compares the configured profile; an offline-mode +// server derives the profile from the name, so it is accepted as it is. +func (c *clientConn) verifyLoginProfile(received, selected loginProfile, joinedSession bool) error { + switch { + case joinedSession: + if !sameProfileIdentity(received, selected) { return fmt.Errorf("login profile mismatch") } - if verifyErr := c.yggdrasil.verifyLoginProfile(receivedProfile); verifyErr != nil { - return fmt.Errorf("verify login profile: %w", verifyErr) + if err := c.yggdrasil.verifyLoginProfile(received); err != nil { + return fmt.Errorf("verify login profile: %w", err) + } + case c.yggdrasil == nil: + if !sameLoginProfile(received, selected) { + return fmt.Errorf("login profile mismatch") } - } else if !sameLoginProfile(receivedProfile, selectedProfile) { - return fmt.Errorf("login profile mismatch") } - loginAcknowledgedLength, err := writePacketWithLength(c.writer, 0x03) - if err != nil { - return fmt.Errorf("write login acknowledged: %w", err) - } - c.reader = newPaddingReader(c.reader, true) - if err = runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil { + return nil +} + +// startProxy runs the startup padding and hands the connection to the tick +// stream. It is called once the login reached the configuration state. +func (c *clientConn) startProxy(loginAcknowledgedLength int) error { + c.reader = newPaddingReader(c.reader, true, c.paddingChannel, c.protocol.configuration) + if err := runPaddingSchedule(c.writer, true, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause, c.paddingChannel, c.protocol.configuration); err != nil { _ = c.Close() // Unblock the startup reader if writing failed. return fmt.Errorf("run startup padding: %w", err) } - packet := newPacketStream(c.reader, c.writer, true) + packet := newTickStream(c.reader, c.writer, true, c.protocol.configuration, c.dataChannel, c.paddingChannel) c.lifecycleMu.Lock() if c.closed { c.lifecycleMu.Unlock() @@ -339,6 +499,10 @@ func (c *clientConn) Close() error { c.lifecycleMu.Unlock() c.closeOnce.Do(func() { close(c.done) }) if packet != nil { + // Write returns once data is queued for the next tick, so a graceful + // close has to flush the last tick instead of dropping it. + _ = c.c.SetWriteDeadline(time.Now().Add(time.Second)) + _ = packet.Flush() packet.Stop() } return c.c.Close() diff --git a/transport/internet/finalmask/xmc/config.go b/transport/internet/finalmask/xmc/config.go index 181c9ee7e..c069ae3ad 100644 --- a/transport/internet/finalmask/xmc/config.go +++ b/transport/internet/finalmask/xmc/config.go @@ -1,10 +1,12 @@ package xmc import ( + "context" "fmt" "math" "time" + "github.com/xtls/xray-core/common/errors" "github.com/xtls/xray-core/common/net" "github.com/xtls/xray-core/transport/internet/finalmask" ) @@ -30,6 +32,49 @@ func (c *Config) wrapClientAuth() (*yggdrasilAuth, error) { ) } +// gameVersion resolves an explicitly configured protocol row. A configured +// value has to be a known row, because a guessed packet id breaks the login in a +// way that looks like a network failure. +func (c *Config) gameVersion() (protocolVersion, error) { + if err := ValidateProtocolVersion(c.ProtocolVersion); err != nil { + return protocolVersion{}, err + } + if c.ProtocolVersion == 0 { + return latestProtocolVersion, nil + } + version, _ := protocolVersionByNumber(Varint(c.ProtocolVersion)) + return version, nil +} + +// clientProtocol resolves the row the client advertises in its handshake. A +// configured protocol_version is used as-is; zero asks the peer for its status, +// because a vanilla server rejects a client that names another version, and the +// status response carries the version its login expects. +// +// The probe is cached per destination, so a normal connection pays it once in a +// while rather than on every dial. A peer that does not answer status (or is +// behind another transport) falls back to the newest row, which is what a +// client of the newest release sends. +func (c *Config) clientProtocol(dest *net.Destination, dialer *finalmask.Dialer) (protocolVersion, error) { + if err := ValidateProtocolVersion(c.ProtocolVersion); err != nil { + return protocolVersion{}, err + } + if c.ProtocolVersion != 0 { + return c.gameVersion() + } + + number, name, err := detectProtocolVersion(dest, c.Hostname, dialer) + if err != nil { + errors.LogWarning(context.Background(), "XMC: cannot detect the peer's protocol version (", err, "), advertising ", latestProtocolVersion.name, " (", latestProtocolVersion.number, "); set protocolVersion to pin it") + return latestProtocolVersion, nil + } + version, ok := protocolVersionByNumber(number) + if !ok { + return protocolVersion{}, fmt.Errorf("the peer reports Minecraft %q (protocol %d), which is not in the supported table (%s); set protocolVersion to override the detection", name, number, protocolVersionRange()) + } + return version, nil +} + func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *finalmask.Dialer) (net.Conn, error) { profiles, err := profilesFromConfig(c.Profiles) if err != nil { @@ -39,6 +84,14 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi if err != nil { return nil, fmt.Errorf("minecraft finalmask: %w", err) } + dataChannel, paddingChannel, err := c.ChannelIDs() + if err != nil { + return nil, fmt.Errorf("minecraft finalmask: %w", err) + } + protocol, err := c.clientProtocol(dest, dialer) + if err != nil { + return nil, fmt.Errorf("minecraft finalmask: %w", err) + } auth, err := c.wrapClientAuth() if err != nil { @@ -56,7 +109,7 @@ func (c *Config) WrapConnClient(conn net.Conn, dest *net.Destination, dialer *fi rsaPublicKey = c.RsaPublicKey } - cc, err := newClientConn(conn, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth) + cc, err := newClientConn(conn, protocol, profiles, c.Password, rsaPublicKey, c.Hostname, paddingSchedule, auth, dataChannel, paddingChannel) if err != nil { return nil, fmt.Errorf("minecraft finalmask: %w", err) } @@ -73,6 +126,10 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) { if err != nil { return nil, fmt.Errorf("minecraft finalmask: %w", err) } + dataChannel, paddingChannel, err := c.ChannelIDs() + if err != nil { + return nil, fmt.Errorf("minecraft finalmask: %w", err) + } var verifier *yggdrasilVerifier if c.Yggdrasil != nil { @@ -85,7 +142,7 @@ func (c *Config) WrapConnServer(conn net.Conn) (net.Conn, error) { return nil, fmt.Errorf("minecraft finalmask: empty profiles") } - cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier) + cc, err := wrapConnServer(conn, profiles, c.Password, c.RsaPrivateKey, c.RsaPublicKey, paddingSchedule, verifier, dataChannel, paddingChannel) if err != nil { return nil, fmt.Errorf("minecraft finalmask: %w", err) } diff --git a/transport/internet/finalmask/xmc/config.pb.go b/transport/internet/finalmask/xmc/config.pb.go index ab8e47adc..4161b0f1e 100644 --- a/transport/internet/finalmask/xmc/config.pb.go +++ b/transport/internet/finalmask/xmc/config.pb.go @@ -189,9 +189,24 @@ type Config struct { Yggdrasil *Yggdrasil `protobuf:"bytes,13,opt,name=yggdrasil,proto3" json:"yggdrasil,omitempty"` // Disables startup padding. The configuration sets this for an explicit // empty "paddings" array, which an unset repeated field cannot express. - NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + NoPadding bool `protobuf:"varint,14,opt,name=no_padding,json=noPadding,proto3" json:"no_padding,omitempty"` + // Custom payload channel that carries the tunnel byte stream, and the one + // that carries startup padding. Both ends must use the same pair; empty + // keeps the built-in default. Both are namespace:path resource locations, + // so vanilla's "minecraft" namespace is rejected: those ids belong to the + // game, and reusing one would collide with a vanilla payload. + DataChannel string `protobuf:"bytes,15,opt,name=data_channel,json=dataChannel,proto3" json:"data_channel,omitempty"` + PaddingChannel string `protobuf:"bytes,16,opt,name=padding_channel,json=paddingChannel,proto3" json:"padding_channel,omitempty"` + // Minecraft release the client advertises in its handshake, as a network + // protocol number (for example 777 for 26.3). Zero probes the peer: the + // client asks for its status and advertises the protocol the peer reports, + // falling back to the newest version the mask knows when the peer does not + // answer (the probe result is cached per destination). Set it to skip the + // probe or to pin a version; the server always follows the version the + // client names. + ProtocolVersion uint32 `protobuf:"varint,17,opt,name=protocol_version,json=protocolVersion,proto3" json:"protocol_version,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *Config) Reset() { @@ -280,6 +295,27 @@ func (x *Config) GetNoPadding() bool { return false } +func (x *Config) GetDataChannel() string { + if x != nil { + return x.DataChannel + } + return "" +} + +func (x *Config) GetPaddingChannel() string { + if x != nil { + return x.PaddingChannel + } + return "" +} + +func (x *Config) GetProtocolVersion() uint32 { + if x != nil { + return x.ProtocolVersion + } + return 0 +} + type Padding struct { state protoimpl.MessageState `protogen:"open.v1"` LengthMin int64 `protobuf:"varint,1,opt,name=length_min,json=lengthMin,proto3" json:"length_min,omitempty"` @@ -379,7 +415,7 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" + "\x03api\x18\x01 \x01(\tR\x03api\x12\x1a\n" + "\busername\x18\x02 \x01(\tR\busername\x12\x1a\n" + "\bpassword\x18\x03 \x01(\tR\bpassword\x12\x16\n" + - "\x06player\x18\x04 \x01(\tR\x06player\"\x9b\x03\n" + + "\x06player\x18\x04 \x01(\tR\x06player\"\x92\x04\n" + "\x06Config\x12\x1a\n" + "\bpassword\x18\x01 \x01(\tR\bpassword\x12&\n" + "\x0frsa_private_key\x18\b \x01(\fR\rrsaPrivateKey\x12$\n" + @@ -390,7 +426,10 @@ const file_transport_internet_finalmask_xmc_config_proto_rawDesc = "" + "\bpaddings\x18\f \x03(\v2..xray.transport.internet.finalmask.xmc.PaddingR\bpaddings\x12N\n" + "\tyggdrasil\x18\r \x01(\v20.xray.transport.internet.finalmask.xmc.YggdrasilR\tyggdrasil\x12\x1d\n" + "\n" + - "no_padding\x18\x0e \x01(\bR\tnoPaddingJ\x04\b\x02\x10\x03\"\x9f\x01\n" + + "no_padding\x18\x0e \x01(\bR\tnoPadding\x12!\n" + + "\fdata_channel\x18\x0f \x01(\tR\vdataChannel\x12'\n" + + "\x0fpadding_channel\x18\x10 \x01(\tR\x0epaddingChannel\x12)\n" + + "\x10protocol_version\x18\x11 \x01(\rR\x0fprotocolVersionJ\x04\b\x02\x10\x03\"\x9f\x01\n" + "\aPadding\x12\x1d\n" + "\n" + "length_min\x18\x01 \x01(\x03R\tlengthMin\x12\x1d\n" + diff --git a/transport/internet/finalmask/xmc/config.proto b/transport/internet/finalmask/xmc/config.proto index 95af7a85b..bd34c87fd 100644 --- a/transport/internet/finalmask/xmc/config.proto +++ b/transport/internet/finalmask/xmc/config.proto @@ -53,6 +53,21 @@ message Config { // Disables startup padding. The configuration sets this for an explicit // empty "paddings" array, which an unset repeated field cannot express. bool no_padding = 14; + // Custom payload channel that carries the tunnel byte stream, and the one + // that carries startup padding. Both ends must use the same pair; empty + // keeps the built-in default. Both are namespace:path resource locations, + // so vanilla's "minecraft" namespace is rejected: those ids belong to the + // game, and reusing one would collide with a vanilla payload. + string data_channel = 15; + string padding_channel = 16; + // Minecraft release the client advertises in its handshake, as a network + // protocol number (for example 777 for 26.3). Zero probes the peer: the + // client asks for its status and advertises the protocol the peer reports, + // falling back to the newest version the mask knows when the peer does not + // answer (the probe result is cached per destination). Set it to skip the + // probe or to pin a version; the server always follows the version the + // client names. + uint32 protocol_version = 17; } message Padding { diff --git a/transport/internet/finalmask/xmc/config_test.go b/transport/internet/finalmask/xmc/config_test.go index e6a829677..6ecd45e26 100644 --- a/transport/internet/finalmask/xmc/config_test.go +++ b/transport/internet/finalmask/xmc/config_test.go @@ -16,10 +16,10 @@ func TestClientRejectsLongLegacyPassword(t *testing.T) { profiles := []loginProfile{{Username: "TestUser"}} publicKey := []byte{0x01} - if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil); err != nil { + if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); err != nil { t.Fatalf("password of %d bytes was rejected: %v", MaxLegacyPasswordLength, err) } - if _, err := newClientConn(client, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil); err == nil { + if _, err := newClientConn(client, latestProtocolVersion, profiles, strings.Repeat("p", MaxLegacyPasswordLength+1), publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel); err == nil { t.Fatal("expected the long password to be rejected") } } @@ -130,7 +130,7 @@ func TestCloseCancelsPaddingPause(t *testing.T) { client, server := net.Pipe() defer server.Close() - conn, err := newClientConn(client, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil) + conn, err := newClientConn(client, latestProtocolVersion, []loginProfile{{Username: "TestUser"}}, "password", []byte{0x01}, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel) if err != nil { t.Fatal(err) } diff --git a/transport/internet/finalmask/xmc/derivation.go b/transport/internet/finalmask/xmc/derivation.go index 9dcb6a92a..998b2fc59 100644 --- a/transport/internet/finalmask/xmc/derivation.go +++ b/transport/internet/finalmask/xmc/derivation.go @@ -1,6 +1,7 @@ package xmc import ( + "bytes" "crypto/rsa" "crypto/sha256" "fmt" @@ -13,9 +14,16 @@ type sha256Stream struct { buf []byte } +// newSHA256Stream returns a stream seeded with a private copy of seed. The +// seed is hashed lazily on every refill, so retaining the caller's slice lets a +// later append on the same base array rewrite an already-created stream. +// DeriveRSAKey builds "-p-prime" and "-q-prime" from one +// password buffer: with a shared array the second append overwrote the first +// stream's seed, both primes then came from the "-q-prime" stream, and the +// resulting N factored at the first step of Fermat's method. func newSHA256Stream(seed []byte) *sha256Stream { return &sha256Stream{ - seed: seed, + seed: bytes.Clone(seed), } } @@ -56,6 +64,8 @@ func derivePrime(stream *sha256Stream) *big.Int { func DeriveRSAKey(password string) (*rsa.PrivateKey, error) { seed := []byte(password) + // Both appends may write into seed's spare capacity; that is harmless + // because each stream keeps its own copy of the bytes it was given. pStream := newSHA256Stream(append(seed, []byte("-p-prime")...)) qStream := newSHA256Stream(append(seed, []byte("-q-prime")...)) diff --git a/transport/internet/finalmask/xmc/derivation_test.go b/transport/internet/finalmask/xmc/derivation_test.go new file mode 100644 index 000000000..e26c0b8b4 --- /dev/null +++ b/transport/internet/finalmask/xmc/derivation_test.go @@ -0,0 +1,241 @@ +package xmc + +import ( + "bytes" + "crypto/rsa" + "crypto/sha256" + "encoding/hex" + "fmt" + "math/big" + "strings" + "sync" + "testing" +) + +// fermatFactorsInOneStep reports whether the public modulus alone discloses the +// private key. One iteration of Fermat's method yields a square exactly when N +// is the product of two primes with a small gap, which is what happens when p +// and q are derived from the same stream (p == q repaired by stepping q to the +// next prime). +func fermatFactorsInOneStep(n *big.Int) bool { + a := new(big.Int).Sqrt(n) + a.Add(a, big.NewInt(1)) + b2 := new(big.Int).Sub(new(big.Int).Mul(a, a), n) + if b2.Sign() < 0 { + return false + } + b := new(big.Int).Sqrt(b2) + return new(big.Int).Mul(b, b).Cmp(b2) == 0 +} + +func requireUsableKey(t *testing.T, password string) *rsa.PrivateKey { + t.Helper() + key, err := DeriveRSAKey(password) + if err != nil { + t.Fatalf("DeriveRSAKey(%q): %v", password, err) + } + if key.N.BitLen() != 1024 { + t.Fatalf("%q: N is %d bits, want 1024", password, key.N.BitLen()) + } + if key.E != 65537 { + t.Fatalf("%q: E is %d, want 65537", password, key.E) + } + if len(key.Primes) != 2 { + t.Fatalf("%q: got %d primes, want 2", password, len(key.Primes)) + } + if key.Primes[0].Cmp(key.Primes[1]) == 0 { + t.Fatalf("%q (%d bytes): p == q", password, len(password)) + } + if fermatFactorsInOneStep(key.N) { + t.Fatalf("%q (%d bytes): N factors at the first Fermat step, p and q are neighbouring primes", password, len(password)) + } + if got := new(big.Int).Mul(key.Primes[0], key.Primes[1]); got.Cmp(key.N) != 0 { + t.Fatalf("%q: p*q != N", password) + } + return key +} + +// TestNewSHA256StreamOwnsItsSeed is the direct regression test for the aliasing +// defect: the stream hashes its seed on every refill, so it must not retain a +// slice whose backing array a caller may still append to. +func TestNewSHA256StreamOwnsItsSeed(t *testing.T) { + password := []byte(strings.Repeat("k", 100)) + // Mimic []byte(password) handing out a buffer with spare capacity, which is + // what made the two DeriveRSAKey appends overlap in the first place. + shared := make([]byte, len(password), len(password)+2*32) + copy(shared, password) + + pStream := newSHA256Stream(append(shared, []byte("-p-prime")...)) + qStream := newSHA256Stream(append(shared, []byte("-q-prime")...)) + + if bytes.HasSuffix(pStream.seed, []byte("-q-prime")) { + t.Fatalf("p stream seed was rewritten by the q stream's append: %q", pStream.seed) + } + if !bytes.HasPrefix(pStream.seed, password) || !bytes.HasSuffix(pStream.seed, []byte("-p-prime")) { + t.Fatalf("p stream seed = %q, want -p-prime", pStream.seed) + } + if !bytes.HasPrefix(qStream.seed, password) || !bytes.HasSuffix(qStream.seed, []byte("-q-prime")) { + t.Fatalf("q stream seed = %q, want -q-prime", qStream.seed) + } + if &pStream.seed[0] == &qStream.seed[0] { + t.Fatal("both streams share one backing array") + } + + // Whatever happens to the caller's buffer afterwards, the streams are fixed. + for i := range shared { + shared[i] = 'z' + } + if !bytes.HasPrefix(pStream.seed, password) || !bytes.HasPrefix(qStream.seed, password) { + t.Fatal("stream seed follows the caller's buffer after construction") + } +} + +func referenceStreamBytes(seed string, blocks int) []byte { + out := make([]byte, 0, blocks*sha256.Size) + for i := 0; i < blocks; i++ { + h := sha256.New() + h.Write([]byte(seed)) + fmt.Fprintf(h, "-%d", i) + out = append(out, h.Sum(nil)...) + } + return out +} + +func TestSHA256StreamMatchesReference(t *testing.T) { + for _, seed := range []string{ + "", + "password", + strings.Repeat("a", 113), + "00000000-0000-0000-0000-000000000000-p-prime", + } { + got := make([]byte, 3*sha256.Size) + if _, err := newSHA256Stream([]byte(seed)).Read(got); err != nil { + t.Fatalf("seed %q: %v", seed, err) + } + want := referenceStreamBytes(seed, 3) + if !bytes.Equal(got, want) { + t.Fatalf("seed %q: keystream mismatch", seed) + } + } +} + +// TestDeriveRSAKeyAllPasswordLengths sweeps every password length the login +// accepts. Lengths whose allocation rounded up left spare capacity for the +// "-p-prime"/"-q-prime" appends (33-40, 49-56, 65-72, 81-88, 97-104, 113 at the +// time of the fix), but the whole range is checked so a change in allocator size +// classes or escape analysis cannot reintroduce the defect unnoticed. +func TestDeriveRSAKeyAllPasswordLengths(t *testing.T) { + for n := 1; n <= MaxLegacyPasswordLength; n++ { + n := n + t.Run(fmt.Sprintf("len-%03d", n), func(t *testing.T) { + requireUsableKey(t, strings.Repeat("a", n)) + }) + } +} + +// TestDeriveRSAKeyBoundaryLengths pins the lengths next to the capacity +// boundaries where the pre-fix code switched between aliasing and reallocating. +func TestDeriveRSAKeyBoundaryLengths(t *testing.T) { + for _, n := range []int{15, 16, 17, 23, 24, 25, 31, 32, 33, 39, 40, 41, 47, 48, 49, 55, 56, 57, 63, 64, 65, 71, 72, 73, 79, 80, 81, 87, 88, 89, 95, 96, 97, 103, 104, 105, 111, 112, 113} { + n := n + t.Run(fmt.Sprintf("len-%03d", n), func(t *testing.T) { + requireUsableKey(t, strings.Repeat("b", n)) + }) + } +} + +// TestDeriveRSAKeyNonASCIIPasswords covers multi-byte passwords: the affected +// ranges are byte lengths, so a 12-character CJK password is a 36-byte one. +func TestDeriveRSAKeyNonASCIIPasswords(t *testing.T) { + passwords := map[string]string{ + "cjk-33-bytes": strings.Repeat("密", 11), + "cjk-36-bytes": strings.Repeat("密", 12), + "emoji-36-bytes": strings.Repeat("🔒", 9), + "mixed-utf8": "密码-Password-密码-0123456789-密码-0123", + "embedded-nul": "abc\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", + "all-high-bytes": strings.Repeat("\xff", 40), + "surrogate-ish-41": strings.Repeat("é", 20) + "x", + } + for name, password := range passwords { + password := password + t.Run(name, func(t *testing.T) { + t.Logf("password is %d bytes", len(password)) + requireUsableKey(t, password) + }) + } +} + +// TestDeriveRSAKeyExtremeInputs keeps the derivation total over sizes far +// outside what the login accepts: it is called from configuration building, so +// it must not panic or depend on a particular capacity. +func TestDeriveRSAKeyExtremeInputs(t *testing.T) { + cases := map[string]string{ + "empty": "", + "one-byte": "x", + "max-accepted": strings.Repeat("m", MaxLegacyPasswordLength), + "just-over-max": strings.Repeat("m", MaxLegacyPasswordLength+1), + "four-kibibytes": strings.Repeat("m", 4096), + } + for name, password := range cases { + password := password + t.Run(name, func(t *testing.T) { + requireUsableKey(t, password) + }) + } +} + +// TestDeriveRSAKeyDeterministic checks that both ends of a connection derive the +// same key, including when several goroutines build configurations at once. +func TestDeriveRSAKeyDeterministic(t *testing.T) { + const password = "00000000-0000-0000-0000-000000000000" + want := requireUsableKey(t, password).N + + const workers = 8 + results := make([]*big.Int, workers) + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func(i int) { + defer wg.Done() + key, err := DeriveRSAKey(password) + if err != nil { + panic(err) + } + results[i] = key.N + }(i) + } + wg.Wait() + + for i, n := range results { + if n.Cmp(want) != 0 { + t.Fatalf("worker %d derived a different modulus", i) + } + } +} + +// TestDeriveRSAKeyKnownAnswers pins the derivation. The key is a wire-level +// shared secret: changing it for an unaffected password would break every +// existing deployment, so the digests below must only ever change on purpose. +// The 8-, 18- and 32-byte entries are byte-identical to what the aliasing code +// derived, which is the compatibility promise of the fix; the 36- and 113-byte +// entries were the ones whose key had to change. +func TestDeriveRSAKeyKnownAnswers(t *testing.T) { + cases := []struct { + password string + nDigest string + }{ + {"password", "cf683eb5c302ca70"}, + {"padding-regression", "b9e1f7f9b936fb8d"}, + {strings.Repeat("a", 32), "6692488374c0e7aa"}, + {"00000000-0000-0000-0000-000000000000", "6d971fd64a5c0981"}, + {strings.Repeat("m", MaxLegacyPasswordLength), "45b0e2f0dd483585"}, + } + for _, c := range cases { + key := requireUsableKey(t, c.password) + digest := sha256.Sum256(key.N.Bytes()) + got := hex.EncodeToString(digest[:8]) + if got != c.nDigest { + t.Fatalf("%d-byte password: N digest %s, want %s (wire-compatibility break)", len(c.password), got, c.nDigest) + } + } +} diff --git a/transport/internet/finalmask/xmc/handshake_oracle_test.go b/transport/internet/finalmask/xmc/handshake_oracle_test.go new file mode 100644 index 000000000..bda73d656 --- /dev/null +++ b/transport/internet/finalmask/xmc/handshake_oracle_test.go @@ -0,0 +1,647 @@ +package xmc + +import ( + "bytes" + "crypto/rand" + "crypto/rsa" + "crypto/x509" + "io" + "math/big" + "net" + "strings" + "sync" + "testing" + "time" +) + +// The Encryption Response is the one place where a peer can get an answer out of +// the mask before it holds any secret, so every check on it has to be +// indistinguishable from every other. These tests drive the real serverConn.login +// over a scripted stream, so what the peer writes and what the server answers are +// both exact and no socket timing is involved. + +// scriptedServer is one XMC server whose login a test drives packet by packet. +type scriptedServer struct { + t *testing.T + + key *rsa.PrivateKey + conn *serverConn + reader *feedReader + writer *syncWriter + + challenge []byte + + // requestLength is how many bytes the Encryption Request occupied, so the + // answer (everything after it) can be decrypted on its own. + requestLength int + + // respond feeds one Encryption Response and returns the server's answer. + respond func(sharedSecret, verifyToken []byte) loginOutcome +} + +// loginOutcome is what a peer observes after it wrote one Encryption Response: +// the bytes the server sent back and the error login() ended with. +type loginOutcome struct { + answer []byte + err error +} + +// newScriptedServer runs login() up to the Encryption Response. The peer sends +// the Login Start a client would and reads the Encryption Request back. +func newScriptedServer(t *testing.T, password string, profiles []loginProfile) *scriptedServer { + t.Helper() + return newScriptedServerAs(t, password, profiles, profiles[0].Username, profiles[0].UUID) +} + +// newScriptedServerAs is newScriptedServer for a peer that logs in as a name the +// profile list does not contain, which is how the whitelist rejection is reached. +func newScriptedServerAs(t *testing.T, password string, profiles []loginProfile, loginName string, loginUUID UUID) *scriptedServer { + t.Helper() + + key, err := DeriveRSAKey("oracle-test-password") + if err != nil { + t.Fatal(err) + } + publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey) + if err != nil { + t.Fatal(err) + } + + var inbound bytes.Buffer + if err := writePacket(&inbound, latestProtocolVersion.login.serverboundLoginStart, new(String(loginName)), &loginUUID); err != nil { + t.Fatal(err) + } + + s := &scriptedServer{ + t: t, + key: key, + reader: newFeedReader(inbound.Bytes()), + writer: &syncWriter{}, + } + s.conn = &serverConn{ + reader: s.reader, + c: &discardConn{}, + state: serverStateHandshake, + protocol: latestProtocolVersion, + profiles: profiles, + password: password, + rsaPrivateKey: key, + rsaPublicKey: publicKey, + dataChannel: DefaultDataChannel, + paddingChannel: DefaultPaddingChannel, + deadlines: newConnectionDeadlines(&discardConn{}), + done: make(chan struct{}), + yggdrasil: nil, + paddingSchedule: nil, + } + // The Encryption Request goes straight to the peer's socket, so it lands in + // the same buffer the encrypted answer will. + s.conn.writer = s.writer + + loginDone := make(chan error, 1) + go func() { loginDone <- s.conn.login() }() + + // The Encryption Request is one packet and the server writes it as it goes; + // wait until it is fully there instead of reading a writer that is still + // being filled. + deadline := time.Now().Add(10 * time.Second) + for { + // A frame that decoded fully is the only reliable signal that the + // server has written all of it; counting frames would accept a + // half-written one. + if frames, ok := decodeAllPackets(s.writer.snapshot()); ok && frames == 1 { + break + } + if time.Now().After(deadline) { + select { + case loginErr := <-loginDone: + t.Fatalf("login returned before the encryption request: %v (wrote % x)", loginErr, s.writer.snapshot()) + default: + } + t.Fatalf("the server did not write the encryption request: % x", s.writer.snapshot()) + } + time.Sleep(time.Millisecond) + } + + // Parse the Encryption Request from a snapshot: the buffer keeps every byte + // the server writes, later answers included. + written := s.writer.snapshot() + s.requestLength = countFrameBytes(written) + request, err := readPacket(bytes.NewReader(written)) + if err != nil { + t.Fatalf("read encryption request: %v", err) + } + if request.packetID != latestProtocolVersion.login.clientboundHello { + t.Fatalf("login packet id = 0x%02x, want the encryption request", request.packetID) + } + var ( + serverID String + publicKeyField Bytes + verifyToken Bytes + shouldAuthenticate Boolean + ) + if err := request.readFields(&serverID, &publicKeyField, &verifyToken, &shouldAuthenticate); err != nil { + t.Fatalf("read encryption request fields: %v", err) + } + s.challenge = verifyToken + + // Feed the Encryption Response when the peer answers, and collect the + // server's reply afterwards. + s.respond = func(sharedSecret, verifyToken []byte) loginOutcome { + sharedField := Bytes(append([]byte(nil), sharedSecret...)) + tokenField := Bytes(append([]byte(nil), verifyToken...)) + frame, err := encodePacket(latestProtocolVersion.login.serverboundKey, &sharedField, &tokenField) + if err != nil { + t.Fatalf("encode encryption response: %v", err) + } + s.reader.feed(frame) + return s.await(loginDone) + } + + return s +} + +// await waits for login() to return and returns everything the server wrote. +func (s *scriptedServer) await(done <-chan error) loginOutcome { + s.t.Helper() + + select { + case err := <-done: + return loginOutcome{answer: s.answer(), err: err} + case <-time.After(20 * time.Second): + s.t.Fatal("login did not return") + return loginOutcome{} + } +} + +// validToken builds the second block a password-mode client sends: the challenge +// followed by the password, encrypted with the server's public key. +func (s *scriptedServer) validToken(password string) []byte { + s.t.Helper() + plaintext := append(append([]byte(nil), s.challenge...), []byte(password)...) + return s.encrypt(plaintext) +} + +// encrypt builds one PKCS#1 v1.5 block with the public key, exactly as a client +// does with Cipher.getInstance("RSA"). The ciphertext is emitted in its shortest +// form, so the tests also cover a peer whose implementation does not write the +// full modulus width. +func (s *scriptedServer) encrypt(plaintext []byte) []byte { + s.t.Helper() + + k := s.key.Size() + if len(plaintext) > k-11 { + s.t.Fatalf("plaintext of %d bytes does not fit a %d-byte block", len(plaintext), k) + } + + em := make([]byte, k) + em[1] = 0x02 + padding := em[2 : k-1-len(plaintext)] + if _, err := io.ReadFull(rand.Reader, padding); err != nil { + s.t.Fatal(err) + } + for i := range padding { + for padding[i] == 0 { + if _, err := io.ReadFull(rand.Reader, padding[i:i+1]); err != nil { + s.t.Fatal(err) + } + } + } + copy(em[k-len(plaintext):], plaintext) + + m := new(big.Int).SetBytes(em) + c := new(big.Int).Exp(m, big.NewInt(int64(s.key.E)), s.key.N) + return c.Bytes() +} + +// answer returns everything the server wrote after the Encryption Request. +func (s *scriptedServer) answer() []byte { + written := s.writer.snapshot() + if s.requestLength > len(written) { + return nil + } + return append([]byte(nil), written[s.requestLength:]...) +} + +// decryptDisconnect decrypts the answer with the session key the test chose and +// returns the reason of the Login Disconnect inside it. Every server in these +// tests closes with that packet, so a peer that holds the key sees exactly this. +func (s *scriptedServer) decryptDisconnect(answer, sessionKey []byte) string { + s.t.Helper() + + block, err := newAESCipher(sessionKey) + if err != nil { + s.t.Fatal(err) + } + plaintext := make([]byte, len(answer)) + newCFB8Decrypt(block, sessionKey).XORKeyStream(plaintext, answer) + + packet, err := readPacket(bytes.NewReader(plaintext)) + if err != nil { + s.t.Fatalf("decrypt answer: %v (plaintext % x)", err, plaintext) + } + if packet.packetID != latestProtocolVersion.login.clientboundLoginDisconnect { + s.t.Fatalf("packet id in the encrypted answer = 0x%02x, want a login disconnect", packet.packetID) + } + var reason String + if err := packet.readFields(&reason); err != nil { + s.t.Fatalf("read disconnect reason: %v", err) + } + return string(reason) +} + +// decodeAllPackets counts the packets a byte stream holds and reports whether +// the stream ended on a packet boundary and every packet decoded. A single +// frame that grows while it is being written therefore reports ok == false. +func decodeAllPackets(data []byte) (int, bool) { + frames := 0 + rest := data + for len(rest) > 0 { + var length int + size := 0 + for { + if size >= len(rest) { + return frames, false + } + b := rest[size] + length |= int(b&0x7f) << (7 * size) + size++ + if b&0x80 == 0 { + break + } + } + if size+length > len(rest) { + return frames, false + } + if _, err := readPacket(bytes.NewReader(rest[:size+length])); err != nil { + return frames, false + } + rest = rest[size+length:] + frames++ + } + return frames, true +} + +// syncWriter is the peer's socket: login() writes to it from its own goroutine +// while the test reads, so every access is under one lock. +type syncWriter struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (w *syncWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + return w.buf.Write(p) +} + +func (w *syncWriter) snapshot() []byte { + w.mu.Lock() + defer w.mu.Unlock() + return append([]byte(nil), w.buf.Bytes()...) +} + +// feedReader hands a running login() the bytes the peer writes, one feed at a +// time, which a bytes.Reader cannot do once login() holds it. +type feedReader struct { + mu sync.Mutex + cond *sync.Cond + pending []byte + closed bool +} + +func newFeedReader(initial []byte) *feedReader { + r := &feedReader{pending: append([]byte(nil), initial...)} + r.cond = sync.NewCond(&r.mu) + return r +} + +func (r *feedReader) feed(data []byte) { + r.mu.Lock() + defer r.mu.Unlock() + r.pending = append(r.pending, data...) + r.cond.Broadcast() +} + +func (r *feedReader) Read(p []byte) (int, error) { + r.mu.Lock() + defer r.mu.Unlock() + for len(r.pending) == 0 && !r.closed { + r.cond.Wait() + } + if len(r.pending) == 0 { + return 0, io.EOF + } + n := copy(p, r.pending) + r.pending = r.pending[n:] + return n, nil +} + +// discardConn satisfies net.Conn for a scripted server that never blocks. +type discardConn struct{} + +func (discardConn) Read([]byte) (int, error) { return 0, io.EOF } +func (discardConn) Write(p []byte) (int, error) { return len(p), nil } +func (discardConn) Close() error { return nil } +func (discardConn) LocalAddr() net.Addr { return nil } +func (discardConn) RemoteAddr() net.Addr { return nil } +func (discardConn) SetDeadline(time.Time) error { return nil } +func (discardConn) SetReadDeadline(time.Time) error { return nil } +func (discardConn) SetWriteDeadline(time.Time) error { return nil } + +// TestEncryptionResponseBadSecretIsRandom checks the fallback itself: a block +// that does not unpad to exactly sixteen bytes must leave a random secret, not a +// truncated one and not the bytes the peer sent. +func TestEncryptionResponseBadSecretIsRandom(t *testing.T) { + s := newScriptedServer(t, "right-password", []loginProfile{{Username: "TestUser"}}) + + bad := s.encrypt(make([]byte, aesKeyLength)) + bad[0] ^= 0xff + + seen := make(map[string]bool) + for range 8 { + secret, block, ok := s.conn.decryptSharedSecret(bad) + if !ok || block == nil { + t.Fatal("a bad block must still yield a session key to carry on with") + } + seen[string(secret)] = true + } + if len(seen) < 2 { + t.Fatal("every bad block produced the same session key; the fallback is not random") + } + + // A block that unpads to the wrong length must take the same fallback. The + // plaintext is not a session key, so it must not be used as one. + for _, length := range []int{0, 1, 15, 17, 117} { + short := s.encrypt(make([]byte, length)) + first, _, ok := s.conn.decryptSharedSecret(short) + if !ok { + t.Fatalf("%d-byte message: no session key", length) + } + second, _, ok := s.conn.decryptSharedSecret(short) + if !ok { + t.Fatalf("%d-byte message: no session key", length) + } + if bytes.Equal(first, second) { + t.Fatalf("%d-byte message: the fallback secret repeats", length) + } + if len(first) != aesKeyLength { + t.Fatalf("%d-byte message: secret is %d bytes", length, len(first)) + } + } + + secret, _, ok := s.conn.decryptSharedSecret(s.encrypt(make([]byte, aesKeyLength))) + if !ok || !bytes.Equal(secret, make([]byte, aesKeyLength)) { + t.Fatalf("a valid block did not yield its plaintext: %x", secret) + } +} + +// TestEncryptionResponseDoesNotRevealPadding is the regression test for +// GHSA-ggm8-658p-x4mr. The pre-fix server called rsa.DecryptPKCS1v15 and +// returned before installing CFB8 when the padding or the plaintext length was +// wrong, so an invalid block closed the connection with no answer while a valid +// one got an encrypted Login Disconnect: one oracle bit per attempt against a +// static, public RSA key. The fixed server carries on with a random secret, so +// every one of these blocks must produce an answer of exactly the same length as +// the block a peer can verify, and none of them may be rejected before the +// cipher is installed. +func TestEncryptionResponseDoesNotRevealPadding(t *testing.T) { + profiles := []loginProfile{{Username: "TestUser"}} + password := "right-password" + + // Baseline: a well-formed block the peer chose the plaintext of, so it can + // decrypt the answer. The password is wrong, which is what an oracle query + // uses to make the server reach its single rejection. + baselineServer := newScriptedServer(t, password, profiles) + baseline := baselineServer.respond(baselineServer.encrypt(make([]byte, aesKeyLength)), baselineServer.validToken("wrong-password")) + if baseline.err == nil { + t.Fatal("the encryption response with a wrong password was accepted") + } + if len(baseline.answer) == 0 { + t.Fatal("a valid block with a wrong password was not answered inside the encrypted stream") + } + if reason := baselineServer.decryptDisconnect(baseline.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "authservers_down") { + t.Fatalf("baseline disconnect reason = %s", reason) + } + want := len(baseline.answer) + + blocks := []struct { + name string + make func(*scriptedServer) []byte + }{ + {"valid padding, empty message", func(s *scriptedServer) []byte { return s.encrypt(nil) }}, + {"valid padding, one-byte message", func(s *scriptedServer) []byte { return s.encrypt([]byte{1}) }}, + {"valid padding, fifteen-byte message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, 15)) }}, + {"valid padding, seventeen-byte message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, 17)) }}, + {"valid padding, longest message", func(s *scriptedServer) []byte { return s.encrypt(make([]byte, s.key.Size()-11)) }}, + {"ciphertext zero", func(s *scriptedServer) []byte { return make([]byte, s.key.Size()) }}, + {"ciphertext one", func(s *scriptedServer) []byte { + block := make([]byte, s.key.Size()) + block[len(block)-1] = 1 + return block + }}, + {"ciphertext equal to the modulus", func(s *scriptedServer) []byte { + return s.key.N.FillBytes(make([]byte, s.key.Size())) + }}, + {"empty field", func(*scriptedServer) []byte { return nil }}, + {"field longer than the modulus", func(*scriptedServer) []byte { + block := make([]byte, 1023) + if _, err := rand.Read(block); err != nil { + t.Fatal(err) + } + return block + }}, + } + + var fallbackCiphertexts [][]byte + for _, tc := range blocks { + t.Run(tc.name, func(t *testing.T) { + s := newScriptedServer(t, password, profiles) + out := s.respond(tc.make(s), s.validToken("wrong-password")) + if out.err == nil { + t.Fatal("the encryption response was accepted") + } + if strings.Contains(out.err.Error(), "verify token mismatch") { + t.Fatalf("the block was rejected before the cipher was installed: %v", out.err) + } + if len(out.answer) != want { + t.Fatalf("answer is %d bytes, want %d: the response depends on the shared-secret block", len(out.answer), want) + } + fallbackCiphertexts = append(fallbackCiphertexts, out.answer) + }) + } + + // The fallback secret is random per connection, so two runs of the same + // invalid block must not produce the same answer bytes. + t.Run("fallback is fresh per connection", func(t *testing.T) { + if len(fallbackCiphertexts) < 2 { + t.Fatal("not enough answers collected") + } + if bytes.Equal(fallbackCiphertexts[0], fallbackCiphertexts[1]) { + t.Fatal("the same ciphertext was sent for two random session keys") + } + }) + + // The shape of an adaptive query: take a ciphertext that decrypts to a + // session key and perturb it one bit at a time. Whatever padding each + // perturbation happens to produce, the answer must keep the same length. + t.Run("modified captured ciphertexts", func(t *testing.T) { + s := newScriptedServer(t, password, profiles) + captured := s.encrypt(make([]byte, aesKeyLength)) + for i := range 16 { + modified := append([]byte(nil), captured...) + modified[i%len(modified)] ^= 1 << (i % 8) + + query := newScriptedServer(t, password, profiles) + out := query.respond(modified, query.validToken("wrong-password")) + if out.err == nil { + t.Fatal("the modified ciphertext was accepted") + } + if len(out.answer) != want { + t.Fatalf("query %d answered %d bytes, want %d", i, len(out.answer), want) + } + } + }) +} + +// TestEncryptionResponseChallengeIsPubliclyCheckable pins the one difference the +// server keeps on purpose: vanilla validates the challenge before it installs +// the cipher, so a wrong challenge closes the connection unencrypted. The +// challenge is four random bytes the server sent a moment ago, so that shape +// discloses nothing. +func TestEncryptionResponseChallengeIsPubliclyCheckable(t *testing.T) { + profiles := []loginProfile{{Username: "TestUser"}} + + s := newScriptedServer(t, "right-password", profiles) + wrongChallenge := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.encrypt([]byte{1, 2, 3, 4})) + if wrongChallenge.err == nil || !strings.Contains(wrongChallenge.err.Error(), "verify token mismatch") { + t.Fatalf("a wrong challenge was not rejected: %v", wrongChallenge.err) + } + if len(wrongChallenge.answer) != 0 { + t.Fatalf("a bad challenge got %d bytes back, want an unencrypted close", len(wrongChallenge.answer)) + } + + s = newScriptedServer(t, "right-password", profiles) + goodChallenge := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("wrong-password")) + if goodChallenge.err == nil { + t.Fatal("a wrong password was accepted") + } + if len(goodChallenge.answer) == 0 { + t.Fatal("a good challenge with a wrong password was not answered inside the encrypted stream") + } +} + +// TestEncryptionResponseRejectionsAreInsideTheStream checks what a peer that +// holds the session key actually receives: a Login Disconnect, with the reason +// vanilla uses. The whitelist answer is only reachable after the password +// matched, so a guesser never sees it. +func TestEncryptionResponseRejectionsAreInsideTheStream(t *testing.T) { + t.Run("wrong password", func(t *testing.T) { + s := newScriptedServer(t, "right-password", []loginProfile{{Username: "TestUser"}}) + out := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("wrong-password")) + if out.err == nil { + t.Fatal("a wrong password was accepted") + } + if reason := s.decryptDisconnect(out.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "multiplayer.disconnect.authservers_down") { + t.Fatalf("disconnect reason = %s", reason) + } + }) + + t.Run("unknown profile", func(t *testing.T) { + profiles := []loginProfile{{Username: "Known", UUID: UUID{9, 9, 9}}} + + s := newScriptedServerAs(t, "right-password", profiles, "TestUser", UUID{1, 2, 3}) + out := s.respond(s.encrypt(make([]byte, aesKeyLength)), s.validToken("right-password")) + if out.err == nil { + t.Fatal("an unknown profile was accepted") + } + if reason := s.decryptDisconnect(out.answer, make([]byte, aesKeyLength)); !strings.Contains(reason, "not white-listed") { + t.Fatalf("disconnect reason = %s", reason) + } + + // The same answer, from a peer that sent a block it cannot use, must be + // the same length: the whitelist rejection cannot become an oracle for + // the block either. + bad := newScriptedServerAs(t, "right-password", profiles, "TestUser", UUID{1, 2, 3}) + badOut := bad.respond(make([]byte, bad.key.Size()), bad.validToken("right-password")) + if badOut.err == nil { + t.Fatal("an unknown profile with an invalid shared secret was accepted") + } + if len(badOut.answer) != len(out.answer) { + t.Fatalf("invalid shared secret answered %d bytes, valid one %d", len(badOut.answer), len(out.answer)) + } + }) +} + +// TestEncryptionResponseExtremeFields checks the shapes at the edges of the two +// fields: they must fail cleanly, without a panic and without a different shape +// than any other failure, and the field-length limit itself is the only place +// where the packet is refused before decryption - which is public framing the +// peer chose. +func TestEncryptionResponseExtremeFields(t *testing.T) { + profiles := []loginProfile{{Username: "TestUser"}} + + baseline := func(t *testing.T, shared, token []byte) loginOutcome { + t.Helper() + s := newScriptedServer(t, "right-password", profiles) + return s.respond(shared, token) + } + + t.Run("empty token field", func(t *testing.T) { + out := baseline(t, make([]byte, 128), nil) + if out.err == nil || !strings.Contains(out.err.Error(), "verify token mismatch") { + t.Fatalf("empty token: %v", out.err) + } + if len(out.answer) != 0 { + t.Fatalf("empty token got %d bytes", len(out.answer)) + } + }) + + t.Run("token field one byte under the packet field limit", func(t *testing.T) { + out := baseline(t, make([]byte, 128), make([]byte, 1023)) + if out.err == nil || !strings.Contains(out.err.Error(), "verify token mismatch") { + t.Fatalf("oversized token: %v", out.err) + } + if len(out.answer) != 0 { + t.Fatalf("oversized token got %d bytes", len(out.answer)) + } + }) + + t.Run("token field at the packet field limit", func(t *testing.T) { + out := baseline(t, make([]byte, 128), make([]byte, 1024)) + if out.err == nil || !strings.Contains(out.err.Error(), "read encrypt response") { + t.Fatalf("token field at the limit: %v", out.err) + } + if len(out.answer) != 0 { + t.Fatalf("token field at the limit got %d bytes", len(out.answer)) + } + }) + + t.Run("shared secret field at the packet field limit", func(t *testing.T) { + out := baseline(t, make([]byte, 1024), nil) + if out.err == nil || !strings.Contains(out.err.Error(), "read encrypt response") { + t.Fatalf("shared secret field at the limit: %v", out.err) + } + if len(out.answer) != 0 { + t.Fatalf("shared secret field at the limit got %d bytes", len(out.answer)) + } + }) +} + +// countFrameBytes returns the byte length of the first frame in data. +func countFrameBytes(data []byte) int { + var length int + size := 0 + for { + if size >= len(data) { + return len(data) + } + b := data[size] + length |= int(b&0x7f) << (7 * size) + size++ + if b&0x80 == 0 { + break + } + } + return size + length +} diff --git a/transport/internet/finalmask/xmc/handshake_secret.go b/transport/internet/finalmask/xmc/handshake_secret.go new file mode 100644 index 000000000..1a711a6b6 --- /dev/null +++ b/transport/internet/finalmask/xmc/handshake_secret.go @@ -0,0 +1,91 @@ +package xmc + +import ( + "crypto/cipher" + "crypto/rand" + "crypto/rsa" + "crypto/subtle" +) + +const ( + // aesKeyLength is the shared secret length vanilla's Crypt counts its + // cipher on, and the length an XMC client encrypts. + aesKeyLength = 16 +) + +// decryptSharedSecret recovers the AES shared secret and builds its cipher block +// without turning the Encryption Response into a Bleichenbacher oracle. +// +// The wire format is a bare RSA / PKCS#1 v1.5 block, because that is what a +// vanilla client writes (Crypt.encryptUsingKey -> Cipher.getInstance("RSA") -> +// doFinal) and a mask that answered anything else would stop pairing with one. +// Reading it with rsa.DecryptPKCS1v15 and acting on the error - which is what +// this server used to do - lets a peer tell a valid block from an invalid one +// without knowing the key. The key is static (derived from the password) and +// public, so a captured shared secret could then be attacked offline forever. +// +// rsa.DecryptPKCS1v15SessionKey is the RFC 3218 countermeasure, and the one the +// advisory names: a random sixteen-byte secret is chosen first, the block is +// decrypted into it, and the random value survives unless the plaintext is +// exactly sixteen bytes. The padding verdict and the length verdict are folded +// into one constant-time copy, so neither is reported; the private-key operation +// runs on the constant-time FIPS module and the padding scan is branch-free. +// Nothing downstream can branch on the padding either, because a peer that did +// not send a valid block does not learn the secret the server carries on with. +// +// The challenge block is the opposite case and keeps vanilla's behaviour; see +// decryptVerifyToken. +func (c *serverConn) decryptSharedSecret(encryptedSharedSecret []byte) ([]byte, cipher.Block, bool) { + secret := make([]byte, aesKeyLength) + if _, err := rand.Read(secret); err != nil { + return nil, nil, false + } + + // An error here means the field did not decode to a number below the + // modulus: it was longer than the modulus, or equal to or above N. Both are + // properties of the peer's own bytes, not a padding verdict, and the random + // secret stands either way, so the error is dropped on purpose. + _ = rsa.DecryptPKCS1v15SessionKey(nil, c.rsaPrivateKey, encryptedSharedSecret, secret) + + // A secret the AES layer cannot use cannot happen here - the buffer is + // sixteen bytes either way - but the caller must not be able to reach a + // panic through it, so it folds into the same boolean. + block, err := newAESCipher(secret) + if err != nil { + return nil, nil, false + } + return secret, block, true +} + +// decryptVerifyToken recovers the challenge block. It is not a secret-bearing +// plaintext: the challenge is the four random bytes the server sent a moment +// ago, so a failed padding here discloses nothing that is not already public. +// Vanilla treats it the same way (ServerboundKeyPacket.isChallengeValid turns +// bad padding into the same protocol error a wrong challenge produces), and the +// outcome is the one difference vanilla draws too: a bad token closes the +// connection before the cipher is installed, a good one fails inside it. +// +// Unlike the shared secret this must return the whole message, because password +// mode carries the password after the challenge in the same block, so +// rsa.DecryptPKCS1v15 is the right call: its error is the public padding +// verdict vanilla already draws, and its length is not secret. +func decryptVerifyToken(key *rsa.PrivateKey, encryptedVerifyToken []byte) ([]byte, bool) { + plaintext, err := rsa.DecryptPKCS1v15(nil, key, encryptedVerifyToken) + if err != nil { + return nil, false + } + return plaintext, true +} + +// challengesEqual compares the challenge the server sent with the plaintext the +// peer returned. In password mode the password follows the challenge in the same +// block, so a longer plaintext that starts with the challenge is a match; +// vanilla compares the whole plaintext, which works there because its client +// sends the challenge alone. The comparison is constant time, and only the +// length check is not, which is public data deciding a public question. +func challengesEqual(want, got []byte) bool { + if len(got) < len(want) { + return false + } + return subtle.ConstantTimeCompare(want, got[:len(want)]) == 1 +} diff --git a/transport/internet/finalmask/xmc/handshake_test.go b/transport/internet/finalmask/xmc/handshake_test.go index 868b23053..0395d938b 100644 --- a/transport/internet/finalmask/xmc/handshake_test.go +++ b/transport/internet/finalmask/xmc/handshake_test.go @@ -9,10 +9,22 @@ import ( "time" ) +// TestHandshakeWithBidirectionalPadding performs the whole login for the oldest +// and the newest row: 1.21.1 has no Login Finished session id, 26.3 does, so the +// test covers both packet shapes end to end. func TestHandshakeWithBidirectionalPadding(t *testing.T) { + for _, version := range []protocolVersion{protocolVersions[0], latestProtocolVersion} { + t.Run(version.name, func(t *testing.T) { + testHandshakeVersions(t, version) + }) + } +} + +func testHandshakeVersions(t *testing.T, version protocolVersion) { + t.Helper() t.Run("pipe", func(t *testing.T) { client, server := net.Pipe() - testHandshakeWithPadding(t, client, server, 64*1024) + testHandshakeWithPadding(t, version, client, server, 64*1024) }) t.Run("tcp", func(t *testing.T) { listener, err := net.ListenTCP("tcp", &net.TCPAddr{IP: net.IPv4(127, 0, 0, 1)}) @@ -38,11 +50,11 @@ func TestHandshakeWithBidirectionalPadding(t *testing.T) { t.Fatal(err) } } - testHandshakeWithPadding(t, client, server, maxPaddingTurnLength) + testHandshakeWithPadding(t, version, client, server, maxPaddingTurnLength) }) } -func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, length int64) { +func testHandshakeWithPadding(t *testing.T, version protocolVersion, clientRaw, serverRaw net.Conn, length int64) { t.Helper() defer clientRaw.Close() defer serverRaw.Close() @@ -72,12 +84,12 @@ func testHandshakeWithPadding(t *testing.T, clientRaw, serverRaw net.Conn, lengt if err != nil { t.Fatal(err) } - client, err := newClientConn(clientRaw, profiles, "password", publicKey, "localhost", paddingSchedule, nil) + client, err := newClientConn(clientRaw, version, profiles, "password", publicKey, "localhost", paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel) if err != nil { t.Fatal(err) } defer client.Close() - server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil) + server, err := wrapConnServer(serverRaw, profiles, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, paddingSchedule, nil, DefaultDataChannel, DefaultPaddingChannel) if err != nil { t.Fatal(err) } diff --git a/transport/internet/finalmask/xmc/login_flow_test.go b/transport/internet/finalmask/xmc/login_flow_test.go new file mode 100644 index 000000000..8da3c81af --- /dev/null +++ b/transport/internet/finalmask/xmc/login_flow_test.go @@ -0,0 +1,308 @@ +package xmc + +import ( + "bytes" + "crypto/x509" + "io" + "net" + "strings" + "testing" + "time" +) + +func newLoginTestClient(t *testing.T, conn net.Conn, version protocolVersion) *clientConn { + t.Helper() + key, err := DeriveRSAKey("login-flow") + if err != nil { + t.Fatal(err) + } + publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey) + if err != nil { + t.Fatal(err) + } + client, err := newClientConn(conn, version, []loginProfile{{Username: "TestUser"}}, "password", publicKey, "localhost", nil, nil, DefaultDataChannel, DefaultPaddingChannel) + if err != nil { + t.Fatal(err) + } + return client +} + +// TestClientHandshakeAdvertisesConfiguredVersion checks that the handshake +// carries the row selected in the configuration, which is what lets one binary +// pair with servers of different releases. +func TestClientHandshakeAdvertisesConfiguredVersion(t *testing.T) { + for _, number := range []Varint{767, 775, 777} { + version, ok := protocolVersionByNumber(number) + if !ok { + t.Fatalf("protocol %d is missing from the table", number) + } + clientRaw, serverRaw := net.Pipe() + client := newLoginTestClient(t, clientRaw, version) + go func() { _ = client.handshake() }() + + if err := serverRaw.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatal(err) + } + packet, err := readPacket(serverRaw) + if err != nil { + t.Fatalf("protocol %d: read handshake: %v", number, err) + } + if packet.packetID != handshakeServerboundIntention { + t.Fatalf("protocol %d: handshake packet id = 0x%02x", number, packet.packetID) + } + var ( + gotNumber Varint + address String + port UnsignedShort + nextState Varint + ) + if err := packet.readFields(&gotNumber, &address, &port, &nextState); err != nil { + t.Fatalf("protocol %d: read handshake fields: %v", number, err) + } + if gotNumber != number { + t.Fatalf("handshake advertised %d, want %d", gotNumber, number) + } + if nextState != 2 { + t.Fatalf("handshake intent = %d, want login (2)", nextState) + } + + _ = clientRaw.Close() + _ = serverRaw.Close() + } +} + +// TestClientLoginAnswers checks the two optional login exchanges a vanilla 26.x +// client answers: a custom query gets a null payload, a cookie request gets an +// absent cookie. Both use the ids of the selected version. +func TestClientLoginAnswers(t *testing.T) { + version := latestProtocolVersion + + t.Run("custom query", func(t *testing.T) { + var wire, out bytes.Buffer + transactionID := Varint(7) + if err := writePacket(&wire, version.login.clientboundCustomQuery, &transactionID, new(String("test:query"))); err != nil { + t.Fatal(err) + } + request, err := readPacket(&wire) + if err != nil { + t.Fatal(err) + } + client := &clientConn{protocol: version, writer: &out} + if err := client.answerCustomQuery(request); err != nil { + t.Fatal(err) + } + answer, err := readPacket(&out) + if err != nil { + t.Fatal(err) + } + if answer.packetID != version.login.serverboundCustomQueryAnswer { + t.Fatalf("answer packet id = 0x%02x", answer.packetID) + } + // transaction id 7, then the nullable payload marker for "no payload". + if !bytes.Equal(answer.data, []byte{0x07, 0x00}) { + t.Fatalf("answer body = %x", answer.data) + } + }) + + t.Run("cookie request", func(t *testing.T) { + var wire, out bytes.Buffer + if err := writePacket(&wire, version.login.clientboundCookieRequest, new(String("test:cookie"))); err != nil { + t.Fatal(err) + } + request, err := readPacket(&wire) + if err != nil { + t.Fatal(err) + } + client := &clientConn{protocol: version, writer: &out} + if err := client.answerCookieRequest(request); err != nil { + t.Fatal(err) + } + answer, err := readPacket(&out) + if err != nil { + t.Fatal(err) + } + if answer.packetID != version.login.serverboundCookieResponse { + t.Fatalf("answer packet id = 0x%02x", answer.packetID) + } + var key String + if err := answer.readFields(&key); err != nil { + t.Fatal(err) + } + if string(key) != "test:cookie" { + t.Fatalf("cookie key = %q", string(key)) + } + }) +} + +// TestReadLoginFinished checks both shapes of the packet: before 26.2 the body +// ends after the game profile, from 26.2 on a session id follows it. Trailing +// bytes are ignored, because Mojang has appended a field to this packet before. +func TestReadLoginFinished(t *testing.T) { + for _, version := range []protocolVersion{protocolVersions[0], latestProtocolVersion} { + var ( + wire bytes.Buffer + profile = loginProfile{Username: "TestUser", UUID: UUID{1, 2, 3}} + name = String("TestUser") + ) + fields := []field{&profile.UUID, &name, &profile.Properties} + if version.loginFinishedSessionID { + sessionID := UUID{9, 9, 9} + fields = append(fields, &sessionID) + } + if err := writePacket(&wire, version.login.clientboundLoginFinished, fields...); err != nil { + t.Fatal(err) + } + packet, err := readPacket(&wire) + if err != nil { + t.Fatal(err) + } + + client := &clientConn{protocol: version} + got, err := client.readLoginFinished(packet) + if err != nil { + t.Fatalf("%s (%d): read login finished: %v", version.name, version.number, err) + } + if got.Username != "TestUser" || got.UUID != profile.UUID { + t.Fatalf("%s (%d): profile = %q %x", version.name, version.number, got.Username, got.UUID) + } + + // One missing session id must fail, so the flag cannot silently rot. + if version.loginFinishedSessionID { + var short bytes.Buffer + username := String("TestUser") + if err := writePacket(&short, version.login.clientboundLoginFinished, &profile.UUID, &username, &profile.Properties); err != nil { + t.Fatal(err) + } + packet, err := readPacket(&short) + if err != nil { + t.Fatal(err) + } + if _, err := client.readLoginFinished(packet); err == nil { + t.Fatalf("%s: login finished without a session id was accepted", version.name) + } + } + } +} + +// TestServerRejectsUnknownProtocolVersion checks the server answers a version +// outside the table with the same Login Disconnect a vanilla server sends, +// instead of guessing packet ids. +func TestServerRejectsUnknownProtocolVersion(t *testing.T) { + key, err := DeriveRSAKey("login-flow") + if err != nil { + t.Fatal(err) + } + publicKey, err := x509.MarshalPKIXPublicKey(&key.PublicKey) + if err != nil { + t.Fatal(err) + } + + clientRaw, serverRaw := net.Pipe() + defer clientRaw.Close() + defer serverRaw.Close() + + server, err := wrapConnServer(serverRaw, []loginProfile{{Username: "TestUser"}}, "password", x509.MarshalPKCS1PrivateKey(key), publicKey, nil, nil, DefaultDataChannel, DefaultPaddingChannel) + if err != nil { + t.Fatal(err) + } + handshakeResult := make(chan error, 1) + go func() { handshakeResult <- server.handshake() }() + + if err := clientRaw.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatal(err) + } + var ( + protocolNumber Varint = 999 + address String = "localhost" + port UnsignedShort = 25565 + nextState Varint = 2 + ) + if err := writePacket(clientRaw, handshakeServerboundIntention, &protocolNumber, &address, &port, &nextState); err != nil { + t.Fatal(err) + } + + packet, err := readPacket(clientRaw) + if err != nil { + t.Fatalf("read login disconnect: %v", err) + } + if packet.packetID != latestProtocolVersion.login.clientboundLoginDisconnect { + t.Fatalf("disconnect packet id = 0x%02x", packet.packetID) + } + var reason String + if err := packet.readFields(&reason); err != nil { + t.Fatal(err) + } + if !strings.Contains(string(reason), "multiplayer.disconnect.incompatible") { + t.Fatalf("disconnect reason = %s", string(reason)) + } + + if err := <-handshakeResult; err == nil || !strings.Contains(err.Error(), "unsupported protocol version") { + t.Fatalf("handshake error = %v", err) + } +} + +// TestClientRejectsOfflineLogin checks the client refuses a login that never +// asks for encryption: XMC reproduces the online-mode login, and an offline +// server has none of it. +func TestClientRejectsOfflineLogin(t *testing.T) { + version := latestProtocolVersion + clientRaw, serverRaw := net.Pipe() + defer clientRaw.Close() + defer serverRaw.Close() + + client := newLoginTestClient(t, clientRaw, version) + handshakeResult := make(chan error, 1) + go func() { handshakeResult <- client.handshake() }() + + if err := serverRaw.SetDeadline(time.Now().Add(5 * time.Second)); err != nil { + t.Fatal(err) + } + if _, err := readPacket(serverRaw); err != nil { + t.Fatalf("read handshake: %v", err) + } + if _, err := readPacket(serverRaw); err != nil { + t.Fatalf("read login start: %v", err) + } + + // An offline-mode server answers Login Start with Login Finished directly. + var ( + profile = loginProfile{Username: "TestUser", UUID: UUID{1}} + username = String("TestUser") + session = UUID{9} + ) + if err := writePacket(serverRaw, version.login.clientboundLoginFinished, &profile.UUID, &username, &profile.Properties, &session); err != nil { + t.Fatal(err) + } + + err := <-handshakeResult + if err == nil || !strings.Contains(err.Error(), "offline-mode servers are not supported") { + t.Fatalf("handshake error = %v", err) + } +} + +// TestClientRejectsUnauthenticatedServer checks that a server which still +// encrypts but tells the client not to authenticate is refused in Yggdrasil +// mode: that flag is an offline-mode server. +func TestClientRejectsUnauthenticatedServer(t *testing.T) { + version := latestProtocolVersion + + var wire bytes.Buffer + var ( + serverID String + publicKey Bytes = Bytes{1, 2, 3} + challenge Bytes = Bytes{4, 5, 6, 7} + shouldAuthenticate Boolean + ) + if err := writePacket(&wire, version.login.clientboundHello, &serverID, &publicKey, &challenge, &shouldAuthenticate); err != nil { + t.Fatal(err) + } + request, err := readPacket(&wire) + if err != nil { + t.Fatal(err) + } + + client := &clientConn{protocol: version, writer: io.Discard, yggdrasil: &yggdrasilAuth{}} + if _, _, err := client.handleEncryptionRequest(request, loginProfile{}); err == nil || !strings.Contains(err.Error(), "offline-mode servers are not supported") { + t.Fatalf("handle encryption request error = %v", err) + } +} diff --git a/transport/internet/finalmask/xmc/packet_stream.go b/transport/internet/finalmask/xmc/packet_stream.go index bb4f937eb..fcae21076 100644 --- a/transport/internet/finalmask/xmc/packet_stream.go +++ b/transport/internet/finalmask/xmc/packet_stream.go @@ -4,52 +4,173 @@ import ( "bytes" "fmt" "io" + "net" "sync" "sync/atomic" "time" ) const ( - configurationClientboundCustomPayload = 0x01 - configurationServerboundCustomPayload = 0x02 - configurationKeepAlive = 0x04 - - packetChannel = "xmc:data" maxPacketData = 24 * 1024 keepAlivePeriod = 15 * time.Second + + // tickInterval is one Minecraft game tick. After the handshake the proxy + // stream is emitted in one batch per tick so that the connection keeps the + // 20 Hz shape of a real client instead of turning into a bulk TCP stream. + tickInterval = 50 * time.Millisecond + // maxQueuedData bounds proxy data waiting for the next tick. Write blocks + // once the queue is full, so a slow peer pushes back to the proxy instead + // of growing memory without bound. + maxQueuedData = 4 * 1024 * 1024 + // tickPaddingSize keeps every tick non-empty in both directions, like the + // small per-tick packets a real client and server keep sending while idle. + tickPaddingSize = 1 ) -// packetStream carries the raw proxy byte stream in Minecraft configuration +// tickStream carries the raw proxy byte stream in Minecraft configuration // custom payload packets. The configuration state provides bidirectional // payload packets and keep-alives without requiring version-specific world data. -type packetStream struct { +// +// Proxy writes are queued and flushed once per game tick (50 ms). Each tick +// always emits at least one small padding frame, so an idle connection keeps +// the same 20 Hz cadence as a real client. Data that does not fit in one +// payload is split over several payloads in the same tick, which keeps the +// per-tick burst shape without an artificial bandwidth cap. +type tickStream struct { reader io.Reader writer io.Writer isClient bool + // packetIDs are the configuration-state ids of the negotiated version: the + // custom payload pair that carries the tunnel plus the keep-alives, pings, + // cookies and disconnects a peer may send before the tunnel starts. + packetIDs configurationPacketIDs + + // Configured custom payload channels: the data one carries proxy bytes, the + // padding one keeps an idle tick non-empty. Both ends must use the same pair. + dataChannel string + paddingChannel string + readMu sync.Mutex - writeMu sync.Mutex pending []byte + writeMu sync.Mutex + + queueMu sync.Mutex + queueCond *sync.Cond + queue []byte + closed bool + keepAliveID atomic.Int64 done chan struct{} stopOnce sync.Once } -func newPacketStream(reader io.Reader, writer io.Writer, isClient bool) *packetStream { - s := &packetStream{ - reader: reader, - writer: writer, - isClient: isClient, - done: make(chan struct{}), +func newTickStream(reader io.Reader, writer io.Writer, isClient bool, packetIDs configurationPacketIDs, dataChannel, paddingChannel string) *tickStream { + s := &tickStream{ + reader: reader, + writer: writer, + isClient: isClient, + packetIDs: packetIDs, + dataChannel: dataChannel, + paddingChannel: paddingChannel, + done: make(chan struct{}), } + s.queueCond = sync.NewCond(&s.queueMu) + go s.tickLoop() if !isClient { go s.keepAliveLoop() } return s } -func (s *packetStream) Read(p []byte) (int, error) { +func (s *tickStream) tickLoop() { + ticker := time.NewTicker(tickInterval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + if err := s.flushTick(); err != nil { + s.Stop() + return + } + case <-s.done: + return + } + } +} + +// flushTick writes one game tick worth of packets in a single network write: +// queued proxy data first, then one small padding frame. Data is split into +// payloads of at most maxPacketData bytes, but every payload stays in this +// tick's batch, so a busy connection looks like Minecraft chunk bursts rather +// than a continuous stream. +func (s *tickStream) flushTick() error { + s.writeMu.Lock() + defer s.writeMu.Unlock() + + data := s.takeQueue() + + var batch bytes.Buffer + if err := s.writeDataPackets(&batch, data); err != nil { + return err + } + if err := writeCustomPayload(&batch, s.localCustomPayloadID(), s.paddingChannel, make([]byte, tickPaddingSize)); err != nil { + return err + } + + if _, err := s.writer.Write(batch.Bytes()); err != nil { + return fmt.Errorf("write minecraft tick: %w", err) + } + return nil +} + +// Flush writes queued proxy data immediately instead of waiting for the next +// tick. Close uses it so the last bytes are not dropped after Write returned. +func (s *tickStream) Flush() error { + s.writeMu.Lock() + defer s.writeMu.Unlock() + + data := s.takeQueue() + if len(data) == 0 { + return nil + } + + var batch bytes.Buffer + if err := s.writeDataPackets(&batch, data); err != nil { + return err + } + _, err := s.writer.Write(batch.Bytes()) + return err +} + +func (s *tickStream) takeQueue() []byte { + s.queueMu.Lock() + defer s.queueMu.Unlock() + data := s.queue + s.queue = nil + s.queueCond.Broadcast() + return data +} + +func (s *tickStream) writeDataPackets(batch *bytes.Buffer, data []byte) error { + for len(data) > 0 { + n := min(len(data), maxPacketData) + if err := writeCustomPayload(batch, s.localCustomPayloadID(), s.dataChannel, data[:n]); err != nil { + return err + } + data = data[n:] + } + return nil +} + +func writeCustomPayload(w io.Writer, packetID int, channel string, payload []byte) error { + name := String(channel) + data := RestBytes(payload) + return writePacket(w, packetID, &name, &data) +} + +func (s *tickStream) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } @@ -70,7 +191,7 @@ func (s *packetStream) Read(p []byte) (int, error) { } if packet.packetID == s.remoteCustomPayloadID() { - payload, ok, err := parseCustomPayload(packet) + payload, ok, err := parseCustomPayload(packet, s.dataChannel) if err != nil { return 0, err } @@ -85,70 +206,99 @@ func (s *packetStream) Read(p []byte) (int, error) { return n, nil } - if packet.packetID == configurationKeepAlive { + // Everything else in this state is server chatter: the client answers + // what a vanilla client answers and skips the rest (registry data, tags, + // dialogs...), which is what keeps it working across releases. The server + // side only reads tunnel data, so it skips all of it. + if !s.isClient { + continue + } + + switch packet.packetID { + case s.packetIDs.clientboundKeepAlive: var id Long if err := packet.readFields(&id); err != nil { return 0, fmt.Errorf("read minecraft keep-alive: %w", err) } - if s.isClient { - if err := s.writeKeepAlive(id); err != nil { - return 0, err - } + if err := s.writeKeepAlive(s.packetIDs.serverboundKeepAlive, id); err != nil { + return 0, err } + + case s.packetIDs.clientboundPing: + // Configuration Ping is answered with Pong, like a real client. The + // id is a plain 32-bit integer here, not a varint. + var id Int + if err := packet.readFields(&id); err != nil { + return 0, fmt.Errorf("read minecraft ping: %w", err) + } + if err := s.writePong(id); err != nil { + return 0, err + } + + case s.packetIDs.clientboundCookieRequest: + if err := s.writeCookieResponse(packet); err != nil { + return 0, err + } + + case s.packetIDs.clientboundDisconnect: + var reason String + _ = packet.readFields(&reason) + return 0, fmt.Errorf("minecraft disconnected: %s", string(reason)) } } } -func (s *packetStream) Write(p []byte) (int, error) { +func (s *tickStream) Write(p []byte) (int, error) { if len(p) == 0 { return 0, nil } - s.writeMu.Lock() - defer s.writeMu.Unlock() - - written := 0 - for written < len(p) { - end := written + maxPacketData - if end > len(p) { - end = len(p) - } - channel := String(packetChannel) - payload := RestBytes(p[written:end]) - if err := writePacket(s.writer, s.localCustomPayloadID(), &channel, &payload); err != nil { - return written, fmt.Errorf("write minecraft custom payload: %w", err) - } - written = end + s.queueMu.Lock() + for len(s.queue) >= maxQueuedData && !s.closed { + s.queueCond.Wait() } + if s.closed { + s.queueMu.Unlock() + return 0, net.ErrClosed + } + s.queue = append(s.queue, p...) + s.queueMu.Unlock() - return written, nil + return len(p), nil } -func (s *packetStream) Stop() { - s.stopOnce.Do(func() { close(s.done) }) +func (s *tickStream) Stop() { + s.stopOnce.Do(func() { + s.queueMu.Lock() + s.closed = true + s.queue = nil + s.queueCond.Broadcast() + s.queueMu.Unlock() + close(s.done) + }) } -func (s *packetStream) localCustomPayloadID() int { +func (s *tickStream) localCustomPayloadID() int { if s.isClient { - return configurationServerboundCustomPayload + return s.packetIDs.serverboundCustomPayload } - return configurationClientboundCustomPayload + return s.packetIDs.clientboundCustomPayload } -func (s *packetStream) remoteCustomPayloadID() int { +func (s *tickStream) remoteCustomPayloadID() int { if s.isClient { - return configurationClientboundCustomPayload + return s.packetIDs.clientboundCustomPayload } - return configurationServerboundCustomPayload + return s.packetIDs.serverboundCustomPayload } -func parseCustomPayload(packet *mcPacket) ([]byte, bool, error) { +func parseCustomPayload(packet *mcPacket, dataChannel string) ([]byte, bool, error) { r := bytes.NewReader(packet.data) var channel String if err := channel.readFrom(r); err != nil { return nil, false, fmt.Errorf("read minecraft custom payload channel: %w", err) } - if string(channel) != packetChannel { + if string(channel) != dataChannel { return nil, false, nil } payload := make([]byte, r.Len()) @@ -158,23 +308,49 @@ func parseCustomPayload(packet *mcPacket) ([]byte, bool, error) { return payload, true, nil } -func (s *packetStream) writeKeepAlive(id Long) error { +func (s *tickStream) writeKeepAlive(packetID int, id Long) error { s.writeMu.Lock() defer s.writeMu.Unlock() - if err := writePacket(s.writer, configurationKeepAlive, &id); err != nil { + if err := writePacket(s.writer, packetID, &id); err != nil { return fmt.Errorf("write minecraft keep-alive: %w", err) } return nil } -func (s *packetStream) keepAliveLoop() { +// writePong answers a configuration Ping, which a vanilla client always does. +func (s *tickStream) writePong(id Int) error { + s.writeMu.Lock() + defer s.writeMu.Unlock() + if err := writePacket(s.writer, s.packetIDs.serverboundPong, &id); err != nil { + return fmt.Errorf("write minecraft pong: %w", err) + } + return nil +} + +// writeCookieResponse answers a cookie request with an absent cookie, which is +// what a client that never received one sends. +func (s *tickStream) writeCookieResponse(request *mcPacket) error { + var key String + if err := request.readFields(&key); err != nil { + return fmt.Errorf("read minecraft cookie request: %w", err) + } + s.writeMu.Lock() + defer s.writeMu.Unlock() + answered := Boolean(false) + if err := writePacket(s.writer, s.packetIDs.serverboundCookieResponse, &key, &answered); err != nil { + return fmt.Errorf("write minecraft cookie response: %w", err) + } + return nil +} + +func (s *tickStream) keepAliveLoop() { ticker := time.NewTicker(keepAlivePeriod) defer ticker.Stop() for { select { case <-ticker.C: id := Long(s.keepAliveID.Add(1)) - if err := s.writeKeepAlive(id); err != nil { + if err := s.writeKeepAlive(s.packetIDs.clientboundKeepAlive, id); err != nil { return } case <-s.done: diff --git a/transport/internet/finalmask/xmc/padding.go b/transport/internet/finalmask/xmc/padding.go index cd9846903..4ed29173a 100644 --- a/transport/internet/finalmask/xmc/padding.go +++ b/transport/internet/finalmask/xmc/padding.go @@ -29,19 +29,97 @@ const ( // every connection, so it is rejected when the configuration is built. maxPaddingScheduleDelay = handshakeTimeout - 10*time.Second - // Frame padding carries the startup padding in ordinary Minecraft custom - // payload packets so that a vanilla server can parse the whole connection - // without taking the pipeline over. The channel is deliberately different - // from the packet stream channel: both ends drop unknown payloads. - paddingFrameChannel = "xmc:pad" // Serverbound custom payload data is capped at 32767 bytes by // ServerboundCustomPayloadPacket; keep the same budget in both directions. maxPaddingFrameDataLength = 32767 - // Length varint, packet id, channel length varint and the channel itself. - paddingFrameOverhead = 1 + 1 + 1 + len(paddingFrameChannel) ) -var maxPaddingFrameLength = paddingFrameLength(maxPaddingFrameDataLength) +// defaultPaddingFraming is the framing of the built-in padding channel. A +// configured channel name changes the frame overhead, so the framing travels +// with the channel instead of being a package constant. +var defaultPaddingFraming = newPaddingFraming(DefaultPaddingChannel) + +// paddingFraming is the custom payload framing of one channel. Frame padding +// carries the startup padding in ordinary Minecraft custom payload packets so +// that a vanilla server can parse the whole connection without taking the +// pipeline over; the channel name decides the frame overhead, so every exact +// frame length the captured presets ask for depends on it. +type paddingFraming struct { + channel string +} + +func newPaddingFraming(channel string) paddingFraming { + return paddingFraming{channel: channel} +} + +// overhead is the length varint, the packet id, the channel length varint and +// the channel itself, for the smallest length varint. +func (f paddingFraming) overhead() int { + return 1 + 1 + 1 + len(f.channel) +} + +func (f paddingFraming) maxFrameLength() int { + return f.frameLength(maxPaddingFrameDataLength) +} + +// frameLength is the wire size of a custom payload frame whose payload body is +// dataLength bytes long. +func (f paddingFraming) frameLength(dataLength int) int { + bodyLength := 1 + 1 + len(f.channel) + dataLength + return varintSize(Varint(bodyLength)) + bodyLength +} + +// frameDataLength is the payload body that makes a frame exactly frameLength +// bytes long. Some lengths are unreachable because the length varint grows in +// steps. +func (f paddingFraming) frameDataLength(frameLength int) (int, bool) { + for overhead := f.overhead(); overhead <= f.overhead()+2; overhead++ { + dataLength := frameLength - overhead + if dataLength < 0 || dataLength > maxPaddingFrameDataLength { + continue + } + if f.frameLength(dataLength) == frameLength { + return dataLength, true + } + } + return 0, false +} + +// plan splits length bytes into reachable frame sizes. The result is exact +// whenever a partition exists; a length below the smallest frame (the captured +// 2-byte turns) is rounded up to that frame. +func (f paddingFraming) plan(length int) ([]int, error) { + if length <= 0 { + return nil, nil + } + overhead := f.overhead() + if length < overhead { + return []int{overhead}, nil + } + maxFrameLength := f.maxFrameLength() + frameLengths := make([]int, 0, length/paddingBufferLength+1) + for remaining := length; remaining > 0; { + candidate := min(remaining, maxFrameLength) + picked := 0 + for ; candidate >= overhead; candidate-- { + if _, ok := f.frameDataLength(candidate); !ok { + continue + } + rest := remaining - candidate + if rest > 0 && rest < overhead { + continue + } + picked = candidate + break + } + if picked == 0 { + return nil, fmt.Errorf("cannot frame %d padding bytes", length) + } + frameLengths = append(frameLengths, picked) + remaining -= picked + } + return frameLengths, nil +} type paddingVariant struct { chunks []int @@ -97,13 +175,14 @@ func pausePadding(done <-chan struct{}, d time.Duration) error { // Minecraft packets that carry nothing to compare an early arrival against, and // the startup reader drains them on its own while this schedule writes. A peer // that stalls is bounded by maxPaddingScheduleDelay instead. -func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error) error { +func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength int, schedule []paddingTurn, sleep func(time.Duration) error, paddingChannel string, packetIDs configurationPacketIDs) error { if len(schedule) == 0 { return nil } if err := validatePaddingSchedule(schedule, firstTurnPrefixLength); err != nil { return err } + framing := newPaddingFraming(paddingChannel) for i, turn := range schedule { prefixLength := 0 @@ -128,7 +207,7 @@ func runPaddingSchedule(writer io.Writer, isClient bool, firstTurnPrefixLength i if err := sleep(delay); err != nil { return err } - if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(isClient)); err != nil { + if _, err := writePaddingTurnFrames(writer, turn, prefixLength, sleep, paddingFramePacketID(packetIDs, isClient), framing); err != nil { return fmt.Errorf("write padding turn %d: %w", i, err) } } @@ -195,18 +274,19 @@ func validatePaddingSchedule(schedule []paddingTurn, firstTurnPrefixLength int) // paddingFramePacketID returns the configuration-state custom payload packet id // used by the side that sends the padding bytes; both values come from the -// vanilla configuration protocol, so no proxy-specific id ever reaches the wire. -func paddingFramePacketID(isClient bool) int { +// negotiated version's configuration protocol, so no proxy-specific id ever +// reaches the wire. +func paddingFramePacketID(packetIDs configurationPacketIDs, isClient bool) int { if isClient { - return configurationServerboundCustomPayload + return packetIDs.serverboundCustomPayload } - return configurationClientboundCustomPayload + return packetIDs.clientboundCustomPayload } // writePaddingTurnFrames writes one padding turn as a sequence of valid // Minecraft custom payload frames. Only the framing is native: payload bodies // stay zero-filled, so the captured traffic shape is kept. -func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int) (int, error) { +func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sleep func(time.Duration) error, packetID int, framing paddingFraming) (int, error) { startDelay, err := randomPaddingDelay(turn.startDelay) if err != nil { return 0, fmt.Errorf("select padding start delay: %w", err) @@ -241,7 +321,7 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle } zeros := make([]byte, maxPaddingFrameDataLength) - channel := String(paddingFrameChannel) + channel := String(framing.channel) written := 0 for i, chunkLength := range chunks { if i < len(delays) { @@ -253,12 +333,12 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle return written, delayErr } } - frameLengths, planErr := paddingFramePlan(chunkLength) + frameLengths, planErr := framing.plan(chunkLength) if planErr != nil { return written, planErr } for _, frameLength := range frameLengths { - dataLength, ok := paddingFrameDataLength(frameLength) + dataLength, ok := framing.frameDataLength(frameLength) if !ok { return written, fmt.Errorf("unframed padding length %d", frameLength) } @@ -272,63 +352,6 @@ func writePaddingTurnFrames(w io.Writer, turn paddingTurn, prefixLength int, sle return written, nil } -// paddingFrameLength is the wire size of a custom payload frame whose payload -// body is dataLength bytes long. -func paddingFrameLength(dataLength int) int { - bodyLength := 1 + 1 + len(paddingFrameChannel) + dataLength - return varintSize(Varint(bodyLength)) + bodyLength -} - -// paddingFrameDataLength is the payload body that makes a frame exactly -// frameLength bytes long. Some lengths are unreachable because the length -// varint grows in steps. -func paddingFrameDataLength(frameLength int) (int, bool) { - for overhead := paddingFrameOverhead; overhead <= paddingFrameOverhead+2; overhead++ { - dataLength := frameLength - overhead - if dataLength < 0 || dataLength > maxPaddingFrameDataLength { - continue - } - if paddingFrameLength(dataLength) == frameLength { - return dataLength, true - } - } - return 0, false -} - -// paddingFramePlan splits length bytes into reachable frame sizes. The result is -// exact whenever a partition exists; a length below the smallest frame (the -// captured 2-byte turns) is rounded up to that frame. -func paddingFramePlan(length int) ([]int, error) { - if length <= 0 { - return nil, nil - } - if length < paddingFrameOverhead { - return []int{paddingFrameOverhead}, nil - } - frameLengths := make([]int, 0, length/paddingBufferLength+1) - for remaining := length; remaining > 0; { - candidate := min(remaining, maxPaddingFrameLength) - picked := 0 - for ; candidate >= paddingFrameOverhead; candidate-- { - if _, ok := paddingFrameDataLength(candidate); !ok { - continue - } - rest := remaining - candidate - if rest > 0 && rest < paddingFrameOverhead { - continue - } - picked = candidate - break - } - if picked == 0 { - return nil, fmt.Errorf("cannot frame %d padding bytes", length) - } - frameLengths = append(frameLengths, picked) - remaining -= picked - } - return frameLengths, nil -} - func selectPaddingVariant(turn paddingTurn, prefixLength int) (int, []int, []paddingDelayRange, error) { if len(turn.variants) == 0 { minimum, maximum := turn.minLength, turn.maxLength diff --git a/transport/internet/finalmask/xmc/padding_frames_test.go b/transport/internet/finalmask/xmc/padding_frames_test.go index a419a6494..fafb302b2 100644 --- a/transport/internet/finalmask/xmc/padding_frames_test.go +++ b/transport/internet/finalmask/xmc/padding_frames_test.go @@ -12,8 +12,8 @@ import ( func TestPaddingFrameDataLengthRoundTrip(t *testing.T) { for dataLength := 0; dataLength <= maxPaddingFrameDataLength; dataLength++ { - frameLength := paddingFrameLength(dataLength) - got, ok := paddingFrameDataLength(frameLength) + frameLength := defaultPaddingFraming.frameLength(dataLength) + got, ok := defaultPaddingFraming.frameDataLength(frameLength) if !ok || got != dataLength { t.Fatalf("data length %d -> frame %d -> data %d (ok=%v)", dataLength, frameLength, got, ok) } @@ -21,18 +21,18 @@ func TestPaddingFrameDataLengthRoundTrip(t *testing.T) { } func TestPaddingFramePlanTotals(t *testing.T) { - lengths := []int{paddingFrameOverhead, paddingFrameOverhead + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, maxPaddingFrameLength - 1, maxPaddingFrameLength, maxPaddingFrameLength + 1, 3 * maxPaddingFrameLength, 1024 * 1024} + lengths := []int{defaultPaddingFraming.overhead(), defaultPaddingFraming.overhead() + 1, 128, 129, 130, 131, 140, 1024, 48 * 1024, defaultPaddingFraming.maxFrameLength() - 1, defaultPaddingFraming.maxFrameLength(), defaultPaddingFraming.maxFrameLength() + 1, 3 * defaultPaddingFraming.maxFrameLength(), 1024 * 1024} for _, length := range lengths { - plan, err := paddingFramePlan(length) + plan, err := defaultPaddingFraming.plan(length) if err != nil { t.Fatalf("plan %d: %v", length, err) } total := 0 for _, frameLength := range plan { - if _, ok := paddingFrameDataLength(frameLength); !ok { + if _, ok := defaultPaddingFraming.frameDataLength(frameLength); !ok { t.Fatalf("plan %d contains unreachable frame %d", length, frameLength) } - if frameLength > maxPaddingFrameLength { + if frameLength > defaultPaddingFraming.maxFrameLength() { t.Fatalf("plan %d contains oversized frame %d", length, frameLength) } total += frameLength @@ -44,11 +44,11 @@ func TestPaddingFramePlanTotals(t *testing.T) { } func TestPaddingFramePlanRoundsUpShortTurn(t *testing.T) { - plan, err := paddingFramePlan(2) + plan, err := defaultPaddingFraming.plan(2) if err != nil { t.Fatal(err) } - if len(plan) != 1 || plan[0] != paddingFrameOverhead { + if len(plan) != 1 || plan[0] != defaultPaddingFraming.overhead() { t.Fatalf("short turn plan = %v", plan) } } @@ -57,12 +57,12 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) { turns := []paddingTurn{ {direction: paddingClientToServer, minLength: 44, maxLength: 44}, {direction: paddingClientToServer, minLength: 2, maxLength: 2}, - {direction: paddingClientToServer, minLength: maxPaddingFrameLength, maxLength: maxPaddingFrameLength}, - {direction: paddingClientToServer, minLength: 3*maxPaddingFrameLength + 7, maxLength: 3*maxPaddingFrameLength + 7}, + {direction: paddingClientToServer, minLength: defaultPaddingFraming.maxFrameLength(), maxLength: defaultPaddingFraming.maxFrameLength()}, + {direction: paddingClientToServer, minLength: 3*defaultPaddingFraming.maxFrameLength() + 7, maxLength: 3*defaultPaddingFraming.maxFrameLength() + 7}, } for i, turn := range turns { var buffer bytes.Buffer - written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationServerboundCustomPayload) + written, err := writePaddingTurnFrames(&buffer, turn, 0, noPaddingPause, configurationPacketIDs121.serverboundCustomPayload, defaultPaddingFraming) if err != nil { t.Fatalf("turn %d: %v", i, err) } @@ -81,10 +81,10 @@ func TestWritePaddingTurnFramesIsMinecraftTraffic(t *testing.T) { if err != nil { t.Fatalf("turn %d frame %d is not a valid packet: %v", i, frames, err) } - if packet.packetID != configurationServerboundCustomPayload { + if packet.packetID != configurationPacketIDs121.serverboundCustomPayload { t.Fatalf("turn %d frame %d has packet id %d", i, frames, packet.packetID) } - _, ok, err := parseCustomPayload(packet) + _, ok, err := parseCustomPayload(packet, DefaultDataChannel) if err != nil { t.Fatalf("turn %d frame %d: %v", i, frames, err) } @@ -107,7 +107,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) { } var out bytes.Buffer - if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause); err != nil { + if err := runPaddingSchedule(&out, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err != nil { t.Fatal(err) } @@ -119,7 +119,7 @@ func TestRunPaddingScheduleLeavesPeerTurnsAlone(t *testing.T) { if err != nil { t.Fatalf("padding stream is not a valid packet stream: %v", err) } - if packet.packetID != configurationServerboundCustomPayload { + if packet.packetID != configurationPacketIDs121.serverboundCustomPayload { t.Fatalf("unexpected packet id %d in padding stream", packet.packetID) } total += before - reader.Len() @@ -135,7 +135,7 @@ func TestRunPaddingScheduleRejectsInvalidSchedule(t *testing.T) { schedule := []paddingTurn{ {direction: paddingServerToClient, minLength: 10, maxLength: 10}, } - if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause); err == nil { + if err := runPaddingSchedule(&bytes.Buffer{}, true, 2, schedule, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err == nil { t.Fatal("expected an error for a prefixed server-to-client first turn") } } @@ -144,7 +144,7 @@ func noPaddingPause(time.Duration) error { return nil } func TestRunPaddingScheduleWithoutTurns(t *testing.T) { var out bytes.Buffer - if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause); err != nil { + if err := runPaddingSchedule(&out, true, 2, nil, noPaddingPause, DefaultPaddingChannel, configurationPacketIDs121); err != nil { t.Fatal(err) } if out.Len() != 0 { @@ -167,7 +167,7 @@ func TestRunPaddingScheduleStopsWhenClosed(t *testing.T) { pauses++ return net.ErrClosed } - err := runPaddingSchedule(&out, true, 2, schedule, sleep) + err := runPaddingSchedule(&out, true, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121) if !errors.Is(err, net.ErrClosed) { t.Fatalf("expected net.ErrClosed, got %v", err) } @@ -208,7 +208,7 @@ func TestPaddingDelayLeadsIntoTheTurn(t *testing.T) { } return nil } - if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep); err != nil { + if err := runPaddingSchedule(recordingWriter{events: &events}, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); err != nil { t.Fatal(err) } return events @@ -246,7 +246,7 @@ func TestPaddingDelayRangeJittersOnlyTheSender(t *testing.T) { } return nil } - if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep); err != nil { + if err := runPaddingSchedule(io.Discard, isClient, 2, schedule, sleep, DefaultPaddingChannel, configurationPacketIDs121); err != nil { t.Fatal(err) } return pauses diff --git a/transport/internet/finalmask/xmc/padding_reader.go b/transport/internet/finalmask/xmc/padding_reader.go index 7f70e3c6a..2d66b9630 100644 --- a/transport/internet/finalmask/xmc/padding_reader.go +++ b/transport/internet/finalmask/xmc/padding_reader.go @@ -19,16 +19,16 @@ type paddingReader struct { // writing. Buffer only the first non-padding packet, then let the caller resume // reading the underlying stream. This keeps memory bounded without requiring // matching padding lengths or an extra end-of-padding packet on the wire. -func newPaddingReader(reader io.Reader, isClient bool) io.Reader { +func newPaddingReader(reader io.Reader, isClient bool, paddingChannel string, packetIDs configurationPacketIDs) io.Reader { first := make(chan paddingReadResult, 1) go func() { - frame, err := readPastPadding(reader, paddingFramePacketID(!isClient)) + frame, err := readPastPadding(reader, paddingFramePacketID(packetIDs, !isClient), paddingChannel) first <- paddingReadResult{frame: frame, err: err} }() return &paddingReader{reader: reader, first: first} } -func readPastPadding(reader io.Reader, packetID int) ([]byte, error) { +func readPastPadding(reader io.Reader, packetID int, paddingChannel string) ([]byte, error) { for { packet, err := readPacket(reader) if err != nil { @@ -36,7 +36,7 @@ func readPastPadding(reader io.Reader, packetID int) ([]byte, error) { } if packet.packetID == packetID { var channel String - if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && channel == paddingFrameChannel { + if err := channel.readFrom(bytes.NewReader(packet.data)); err == nil && string(channel) == paddingChannel { continue } } diff --git a/transport/internet/finalmask/xmc/padding_reader_test.go b/transport/internet/finalmask/xmc/padding_reader_test.go index 8ccdef16a..6bf8a509c 100644 --- a/transport/internet/finalmask/xmc/padding_reader_test.go +++ b/transport/internet/finalmask/xmc/padding_reader_test.go @@ -10,9 +10,9 @@ import ( func TestPaddingReaderPreservesFollowingPackets(t *testing.T) { for _, isClient := range []bool{true, false} { - packetID := paddingFramePacketID(!isClient) + packetID := paddingFramePacketID(configurationPacketIDs121, !isClient) var wire bytes.Buffer - paddingChannel := String(paddingFrameChannel) + paddingChannel := String(DefaultPaddingChannel) padding := RestBytes(make([]byte, 1024)) if err := writePacket(&wire, packetID, &paddingChannel, &padding); err != nil { t.Fatal(err) @@ -24,15 +24,15 @@ func TestPaddingReaderPreservesFollowingPackets(t *testing.T) { t.Fatal(err) } id := Long(42) - if err := writePacket(&want, configurationKeepAlive, &id); err != nil { + if err := writePacket(&want, configurationPacketIDs121.clientboundKeepAlive, &id); err != nil { t.Fatal(err) } - channel := String(packetChannel) + channel := String(DefaultDataChannel) if err := writePacket(&want, packetID, &channel, &payload); err != nil { t.Fatal(err) } wire.Write(want.Bytes()) - got, err := io.ReadAll(newPaddingReader(&wire, isClient)) + got, err := io.ReadAll(newPaddingReader(&wire, isClient, DefaultPaddingChannel, configurationPacketIDs121)) if err != nil { t.Fatal(err) } @@ -52,7 +52,7 @@ func TestPaddingReaderReadErrors(t *testing.T) { {name: "truncated", wire: []byte{2, 1}, err: io.ErrUnexpectedEOF}, } { t.Run(test.name, func(t *testing.T) { - reader := newPaddingReader(bytes.NewReader(test.wire), true) + reader := newPaddingReader(bytes.NewReader(test.wire), true, DefaultPaddingChannel, configurationPacketIDs121) if _, err := reader.Read(make([]byte, 1)); !errors.Is(err, test.err) { t.Fatalf("got %v, want %v", err, test.err) } @@ -63,7 +63,7 @@ func TestPaddingReaderReadErrors(t *testing.T) { func TestPaddingReaderUnblocksOnClose(t *testing.T) { client, server := net.Pipe() defer server.Close() - reader := newPaddingReader(client, true) + reader := newPaddingReader(client, true, DefaultPaddingChannel, configurationPacketIDs121) if n, err := reader.Read(nil); n != 0 || err != nil { t.Fatalf("empty read = %d, %v", n, err) } diff --git a/transport/internet/finalmask/xmc/profile.go b/transport/internet/finalmask/xmc/profile.go index def92e092..664ac3d5a 100644 --- a/transport/internet/finalmask/xmc/profile.go +++ b/transport/internet/finalmask/xmc/profile.go @@ -184,19 +184,18 @@ func propertyListFromYggdrasil(properties []yggdrasilProperty) loginProperties { return result } -func readLoginSuccess(packet *mcPacket) (loginProfile, error) { - var ( - profile loginProfile - username String - ) - if err := packet.readFields(&profile.UUID, &username, &profile.Properties); err != nil { - return loginProfile{}, err - } - profile.Username = string(username) - return profile, nil -} - -func writeLoginSuccess(w io.Writer, profile loginProfile) error { +// writeLoginFinished writes the Login Finished packet. From 26.2 on the packet +// also carries the connection session id, which the client only uses for its +// own telemetry, so one value per process is enough. +func writeLoginFinished(w io.Writer, version protocolVersion, profile loginProfile) error { username := String(profile.Username) - return writePacket(w, 0x02, &profile.UUID, &username, &profile.Properties) + fields := []field{&profile.UUID, &username, &profile.Properties} + if version.loginFinishedSessionID { + sessionID, err := serverSessionID() + if err != nil { + return err + } + fields = append(fields, &sessionID) + } + return writePacket(w, version.login.clientboundLoginFinished, fields...) } diff --git a/transport/internet/finalmask/xmc/protocol.go b/transport/internet/finalmask/xmc/protocol.go index 8b53b4442..f26fd3caf 100644 --- a/transport/internet/finalmask/xmc/protocol.go +++ b/transport/internet/finalmask/xmc/protocol.go @@ -238,6 +238,29 @@ func (v *UnsignedShort) writeTo(w io.Writer) error { return nil } +// Int is a big-endian 32-bit integer, which is how vanilla encodes packet ids +// that are not counting up from zero (Ping, Pong). It is not a Varint: using the +// wrong one decodes as a valid-looking packet and fails later with a decoder +// exception on the peer. +type Int int32 + +func (v *Int) readFrom(r io.Reader) error { + var buf [4]byte + if _, err := io.ReadFull(r, buf[:]); err != nil { + return fmt.Errorf("read int: %w", err) + } + *v = Int(int32(buf[0])<<24 | int32(buf[1])<<16 | int32(buf[2])<<8 | int32(buf[3])) + return nil +} + +func (v *Int) writeTo(w io.Writer) error { + buf := []byte{byte(*v >> 24), byte(*v >> 16), byte(*v >> 8), byte(*v)} + if _, err := w.Write(buf); err != nil { + return fmt.Errorf("write int: %w", err) + } + return nil +} + type Long int64 func (v *Long) readFrom(r io.Reader) error { @@ -443,6 +466,6 @@ func writeFull(w io.Writer, p []byte) error { return nil } -func writeDisconnectPacket(w io.Writer, reason string) error { - return writePacket(w, 0x00, new(String(reason))) +func writeDisconnectPacket(w io.Writer, packetID int, reason string) error { + return writePacket(w, packetID, new(String(reason))) } diff --git a/transport/internet/finalmask/xmc/protocol_probe.go b/transport/internet/finalmask/xmc/protocol_probe.go new file mode 100644 index 000000000..076fe55ed --- /dev/null +++ b/transport/internet/finalmask/xmc/protocol_probe.go @@ -0,0 +1,154 @@ +// Status probe used to pick the protocol version of the peer. +package xmc + +import ( + "encoding/json" + "fmt" + "strconv" + "sync" + "time" + + xnet "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/transport/internet/finalmask" +) + +const ( + // protocolProbeTimeout bounds one status round trip. A peer that cannot + // answer status in this time is not going to answer the login either. + protocolProbeTimeout = 5 * time.Second + // protocolProbeTTL keeps detection off the connection path: a real client + // refreshes a server's status in its server list, not once per join. + protocolProbeTTL = 10 * time.Minute + // maxProtocolProbeEntries bounds the cache. A proxy can dial many different + // destinations, and each entry is three words. + maxProtocolProbeEntries = 256 +) + +// statusVersion is the part of the status JSON the probe reads. Vanilla reports +// its own protocol version there, and the login it accepts is that version. +type statusVersion struct { + Version struct { + Name string `json:"name"` + Protocol int32 `json:"protocol"` + } `json:"version"` +} + +type protocolProbeEntry struct { + number Varint + name string + expires time.Time +} + +var protocolProbeCache = struct { + mu sync.Mutex + entries map[string]protocolProbeEntry +}{entries: make(map[string]protocolProbeEntry)} + +// probeProtocolVersion asks the peer for its status and returns the protocol +// number and release name it reports. +// +// The probe is a second TCP connection to the same destination, exactly what a +// client does when it refreshes a server in its list, so the peer sees nothing +// unusual. It only works when the destination speaks plain Minecraft: for a +// destination behind another transport, set protocol_version instead. +func probeProtocolVersion(dest *xnet.Destination, hostname string, dialer *finalmask.Dialer) (Varint, string, error) { + if dest == nil { + return 0, "", fmt.Errorf("status probe: no destination") + } + if dialer == nil || dialer.DialTCP == nil { + return 0, "", fmt.Errorf("status probe: no TCP dialer") + } + + conn, err := dialer.DialTCP(*dest) + if err != nil { + return 0, "", fmt.Errorf("status probe: dial: %w", err) + } + defer conn.Close() + if err := conn.SetDeadline(time.Now().Add(protocolProbeTimeout)); err != nil { + return 0, "", fmt.Errorf("status probe: set deadline: %w", err) + } + + address := String(hostname) + if address == "" { + address = String(dest.Address.String()) + } + var ( + protocolNumber Varint = latestProtocolVersion.number + port UnsignedShort = UnsignedShort(dest.Port.Value()) + nextState Varint = 1 // status + ) + if err := writePacket(conn, handshakeServerboundIntention, &protocolNumber, &address, &port, &nextState); err != nil { + return 0, "", fmt.Errorf("status probe: write handshake: %w", err) + } + if err := writePacket(conn, statusServerboundRequest); err != nil { + return 0, "", fmt.Errorf("status probe: write status request: %w", err) + } + + packet, err := readPacket(conn) + if err != nil { + return 0, "", fmt.Errorf("status probe: read status response: %w", err) + } + if packet.packetID != statusClientboundResponse { + return 0, "", fmt.Errorf("status probe: unexpected status packet id: 0x%02x", packet.packetID) + } + var payload String + if err := packet.readFields(&payload); err != nil { + return 0, "", fmt.Errorf("status probe: read status payload: %w", err) + } + var status statusVersion + if err := json.Unmarshal([]byte(payload), &status); err != nil { + return 0, "", fmt.Errorf("status probe: decode status response: %w", err) + } + if status.Version.Protocol <= 0 { + return 0, "", fmt.Errorf("status probe: status response has no version") + } + return Varint(status.Version.Protocol), status.Version.Name, nil +} + +// detectProtocolVersion returns the peer's protocol version, reusing a recent +// probe for the same destination. +func detectProtocolVersion(dest *xnet.Destination, hostname string, dialer *finalmask.Dialer) (Varint, string, error) { + key := protocolProbeKey(dest) + now := time.Now() + + protocolProbeCache.mu.Lock() + if entry, ok := protocolProbeCache.entries[key]; ok && entry.expires.After(now) { + protocolProbeCache.mu.Unlock() + return entry.number, entry.name, nil + } + protocolProbeCache.mu.Unlock() + + number, name, err := probeProtocolVersion(dest, hostname, dialer) + if err != nil { + return 0, "", err + } + + protocolProbeCache.mu.Lock() + if len(protocolProbeCache.entries) >= maxProtocolProbeEntries { + for cachedKey, entry := range protocolProbeCache.entries { + if entry.expires.Before(now) { + delete(protocolProbeCache.entries, cachedKey) + } + } + if len(protocolProbeCache.entries) >= maxProtocolProbeEntries { + clear(protocolProbeCache.entries) + } + } + protocolProbeCache.entries[key] = protocolProbeEntry{number: number, name: name, expires: now.Add(protocolProbeTTL)} + protocolProbeCache.mu.Unlock() + return number, name, nil +} + +// forgetProbedVersions drops every cached detection. A login rejected with a +// version mismatch means the cached row is stale (the peer was upgraded, or the +// detection was wrong), so the next attempt has to ask again instead of waiting +// for the TTL. +func forgetProbedVersions() { + protocolProbeCache.mu.Lock() + clear(protocolProbeCache.entries) + protocolProbeCache.mu.Unlock() +} + +func protocolProbeKey(dest *xnet.Destination) string { + return dest.Network.String() + "|" + dest.Address.String() + "|" + strconv.Itoa(int(dest.Port.Value())) +} diff --git a/transport/internet/finalmask/xmc/protocol_probe_test.go b/transport/internet/finalmask/xmc/protocol_probe_test.go new file mode 100644 index 000000000..15615eaed --- /dev/null +++ b/transport/internet/finalmask/xmc/protocol_probe_test.go @@ -0,0 +1,251 @@ +package xmc + +import ( + "fmt" + "net" + "strconv" + "strings" + "testing" + "time" + + xnet "github.com/xtls/xray-core/common/net" + "github.com/xtls/xray-core/transport/internet/finalmask" +) + +// statusTestServer answers exactly one status exchange with the given version. +func statusTestServer(t *testing.T, listener net.Listener, protocol int32, name string) { + t.Helper() + go func() { + conn, err := listener.Accept() + if err != nil { + return + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) + if _, err := readPacket(conn); err != nil { + return + } + if _, err := readPacket(conn); err != nil { + return + } + payload := String(fmt.Sprintf(`{"description":"test","players":{"max":0,"online":0},"version":{"name":%q,"protocol":%d}}`, name, protocol)) + _ = writePacket(conn, statusClientboundResponse, &payload) + }() +} + +func statusTestDestination(t *testing.T, listener net.Listener) xnet.Destination { + t.Helper() + dest, err := xnet.ParseDestination("tcp:" + listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + return dest +} + +func statusTestDialer(dialErr error) *finalmask.Dialer { + return &finalmask.Dialer{DialTCP: func(dest xnet.Destination) (net.Conn, error) { + if dialErr != nil { + return nil, dialErr + } + return net.Dial("tcp", net.JoinHostPort(dest.Address.String(), strconv.Itoa(int(dest.Port.Value())))) + }} +} + +// TestProbeProtocolVersion reads the version out of the status response, which +// is the version the peer's login expects. +func TestProbeProtocolVersion(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + statusTestServer(t, listener, 767, "1.21.1") + + dest := statusTestDestination(t, listener) + number, name, err := probeProtocolVersion(&dest, "localhost", statusTestDialer(nil)) + if err != nil { + t.Fatalf("probe: %v", err) + } + if number != 767 || name != "1.21.1" { + t.Fatalf("probe = %d %q, want 767 \"1.21.1\"", number, name) + } +} + +func TestProbeProtocolVersionRejectsBrokenPeer(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + go func() { + conn, err := listener.Accept() + if err != nil { + return + } + defer conn.Close() + _ = conn.SetDeadline(time.Now().Add(5 * time.Second)) + _, _ = readPacket(conn) + _, _ = readPacket(conn) + payload := String(`{"description":"no version here"}`) + _ = writePacket(conn, statusClientboundResponse, &payload) + }() + + dest := statusTestDestination(t, listener) + if _, _, err := probeProtocolVersion(&dest, "localhost", statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "no version") { + t.Fatalf("probe error = %v", err) + } + + if _, _, err := probeProtocolVersion(&dest, "localhost", nil); err == nil || !strings.Contains(err.Error(), "no TCP dialer") { + t.Fatalf("nil dialer error = %v", err) + } + if _, _, err := probeProtocolVersion(nil, "localhost", statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "no destination") { + t.Fatalf("nil destination error = %v", err) + } +} + +// TestDetectProtocolVersionCaches checks a destination is probed once per TTL: +// the second call must answer from the cache even though dialing now fails. +func TestDetectProtocolVersionCaches(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + statusTestServer(t, listener, 776, "26.2") + dest := statusTestDestination(t, listener) + + number, name, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(nil)) + if err != nil { + t.Fatalf("detect: %v", err) + } + if number != 776 || name != "26.2" { + t.Fatalf("detect = %d %q", number, name) + } + if err := listener.Close(); err != nil { + t.Fatal(err) + } + + number, _, err = detectProtocolVersion(&dest, "localhost", statusTestDialer(fmt.Errorf("must not dial"))) + if err != nil { + t.Fatalf("cached detect: %v", err) + } + if number != 776 { + t.Fatalf("cached detect = %d", number) + } +} + +// TestClientProtocol covers the three ways the client picks its row: a +// configured version, a detected one, and the fallback when the peer does not +// answer status. +func TestClientProtocol(t *testing.T) { + t.Run("configured", func(t *testing.T) { + // No destination and no dialer: a configured version must not probe. + version, err := (&Config{ProtocolVersion: 775}).clientProtocol(nil, nil) + if err != nil || version.number != 775 { + t.Fatalf("configured = %v, %v", version.number, err) + } + }) + + t.Run("detected", func(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + statusTestServer(t, listener, 767, "1.21.1") + dest := statusTestDestination(t, listener) + + version, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil)) + if err != nil || version.number != 767 || version.name != "1.21.1" { + t.Fatalf("detected = %v %q, %v", version.number, version.name, err) + } + }) + + t.Run("unknown", func(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + statusTestServer(t, listener, 999, "999") + dest := statusTestDestination(t, listener) + + if _, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil)); err == nil || !strings.Contains(err.Error(), "not in the supported table") { + t.Fatalf("unknown version error = %v", err) + } + }) + + t.Run("probe failure falls back to the newest row", func(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + address := listener.Addr().String() + if err := listener.Close(); err != nil { + t.Fatal(err) + } + dest, err := xnet.ParseDestination("tcp:" + address) + if err != nil { + t.Fatal(err) + } + + version, err := (&Config{}).clientProtocol(&dest, statusTestDialer(nil)) + if err != nil { + t.Fatalf("fallback: %v", err) + } + if version.number != latestProtocolVersion.number { + t.Fatalf("fallback version = %d, want %d", version.number, latestProtocolVersion.number) + } + }) +} + +// TestForgetProbedVersions covers a stale detection: after a version mismatch +// the cache is dropped, so the next connection probes again instead of reusing +// the row the peer no longer speaks. +func TestForgetProbedVersions(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + statusTestServer(t, listener, 767, "1.21.1") + dest := statusTestDestination(t, listener) + + if number, _, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(nil)); err != nil || number != 767 { + t.Fatalf("detect = %v, %v", number, err) + } + forgetProbedVersions() + + // The peer now reports another version; a cached answer would hide it. + listener2, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener2.Close() + statusTestServer(t, listener2, 775, "26.1") + dest2 := statusTestDestination(t, listener2) + + // A dialer that fails proves the cache was consulted; after forgetting, the + // same destination must probe again. + if err := listener.Close(); err != nil { + t.Fatal(err) + } + if number, _, err := detectProtocolVersion(&dest, "localhost", statusTestDialer(fmt.Errorf("must probe again"))); err == nil { + t.Fatalf("stale cache was reused: %v", number) + } + if number, _, err := detectProtocolVersion(&dest2, "localhost", statusTestDialer(nil)); err != nil || number != 775 { + t.Fatalf("fresh detect = %v, %v", number, err) + } +} + +func TestIsProtocolVersionReject(t *testing.T) { + for _, reason := range []string{ + `{"translate":"multiplayer.disconnect.incompatible","with":["26.3"]}`, + `{"translate":"multiplayer.disconnect.outdated_client","with":["26.3"]}`, + } { + if !isProtocolVersionReject(reason) { + t.Fatalf("%s should be a version reject", reason) + } + } + if isProtocolVersionReject(`{"translate":"multiplayer.disconnect.not_whitelisted"}`) { + t.Fatal("a whitelist reject is not a version reject") + } +} diff --git a/transport/internet/finalmask/xmc/protocol_table.go b/transport/internet/finalmask/xmc/protocol_table.go new file mode 100644 index 000000000..d1cf5052e --- /dev/null +++ b/transport/internet/finalmask/xmc/protocol_table.go @@ -0,0 +1,210 @@ +// Minecraft protocol table. +// +// Every packet id XMC writes or matches is the registration order of the packet +// type in that version's protocol builder, not a value observed in a capture: +// LoginProtocols and ConfigurationProtocols call addPacket in source order and +// both ends dispatch on that index. The table keeps those ids in one place and +// per version, so a new release is a row instead of an edit spread over the +// login, configuration and padding code. +// +// Rows come from two independent sources, and neither is a packet capture: +// +// - 767..775 (1.21.1 .. 26.1): minecraft-data's per-version protocol.json +// (data/pc//protocol.json), which stores the same registration +// order as a {hex id: packet name} mapping; +// - 776..777 (26.2, 26.3): the official jars, LoginProtocols and +// ConfigurationProtocols. +// +// 26.3 is the reason this table exists. It inserts ClientboundPostEffectsPacket +// into the configuration clientbound list at 0x0a, after the keep-alive and +// before store_cookie, so every id behind it moves by one. Every id XMC uses +// stayed put, which is luck rather than design: the list grows by one or two +// packets per release (17 clientbound configuration packets in 1.21.1, 21 in +// 26.3), and an insertion in front of 0x04 would silently break the tunnel. +// Adding a version means adding a row here and an expectation in +// protocol_table_test.go, after diffing the two registration lists. +package xmc + +import ( + "fmt" + "strings" +) + +// handshaking and status packet ids. These have not moved since 1.7 and are +// fixed for every version the table covers. +const ( + handshakeServerboundIntention = 0x00 + statusServerboundRequest = 0x00 + statusServerboundPing = 0x01 + statusClientboundResponse = 0x00 + statusClientboundPong = 0x01 +) + +// loginPacketIDs is the login state of one version. +type loginPacketIDs struct { + // Serverbound (client to server). + serverboundLoginStart int + serverboundKey int + serverboundCustomQueryAnswer int + serverboundLoginAcknowledged int + serverboundCookieResponse int + + // Clientbound (server to client). + clientboundLoginDisconnect int + clientboundHello int + clientboundLoginFinished int + clientboundLoginCompression int + clientboundCustomQuery int + clientboundCookieRequest int +} + +// configurationPacketIDs is the part of the configuration state XMC uses: the +// custom payload pair that carries the tunnel, the keep-alive and ping that +// keep the connection alive like a real one, and the packets that a peer can +// send before the tunnel starts, so that they are recognised instead of being +// mistaken for tunnel data. +type configurationPacketIDs struct { + // Serverbound (client to server). + serverboundClientInformation int + serverboundCookieResponse int + serverboundCustomPayload int + serverboundKeepAlive int + serverboundPong int + + // Clientbound (server to client). + clientboundCookieRequest int + clientboundCustomPayload int + clientboundDisconnect int + clientboundKeepAlive int + clientboundPing int +} + +// protocolVersion describes one Minecraft release for the part of the protocol +// the finalmask depends on. +type protocolVersion struct { + // number is the network protocol version advertised in the handshake and + // reported by the status response. + number Varint + // name is the release name, for example "26.3", as the status response + // reports it. + name string + + login loginPacketIDs + configuration configurationPacketIDs + + // loginFinishedSessionID is set from 26.2 (776) on: Login Finished appends + // the connection session id after the game profile, so the client has to + // read it and the server has to write it. + loginFinishedSessionID bool +} + +// The login and configuration ids that 767..777 share. 26.2 added the session +// id field, and 26.3 inserted a clientbound configuration packet, but none of +// the ids below moved between 1.21.1 and 26.3. +var ( + loginPacketIDs121 = loginPacketIDs{ + serverboundLoginStart: 0x00, + serverboundKey: 0x01, + serverboundCustomQueryAnswer: 0x02, + serverboundLoginAcknowledged: 0x03, + serverboundCookieResponse: 0x04, + + clientboundLoginDisconnect: 0x00, + clientboundHello: 0x01, + clientboundLoginFinished: 0x02, + clientboundLoginCompression: 0x03, + clientboundCustomQuery: 0x04, + clientboundCookieRequest: 0x05, + } + + configurationPacketIDs121 = configurationPacketIDs{ + serverboundClientInformation: 0x00, + serverboundCookieResponse: 0x01, + serverboundCustomPayload: 0x02, + serverboundKeepAlive: 0x04, + serverboundPong: 0x05, + + clientboundCookieRequest: 0x00, + clientboundCustomPayload: 0x01, + clientboundDisconnect: 0x02, + clientboundKeepAlive: 0x04, + clientboundPing: 0x05, + } +) + +// protocolVersions is ordered by protocol number, oldest first. Only releases +// the mod's branches target are listed: the configuration state starts at 1.20.5 +// (766), and XMC is only useful from 1.21 on, so 767 is the oldest row. +// +// Releases that share a protocol number share a row and cannot be told apart on +// the wire; the name is the one the mod's branches use (1.21.2 is 768 like +// 1.21.3, 1.21.7 is 772 like 1.21.8, 1.21.10 is 773 like 1.21.9, and 26.1.1 / +// 26.1.2 are 775 like 26.1). +var protocolVersions = []protocolVersion{ + {number: 767, name: "1.21.1", login: loginPacketIDs121, configuration: configurationPacketIDs121}, + {number: 768, name: "1.21.3", login: loginPacketIDs121, configuration: configurationPacketIDs121}, + {number: 769, name: "1.21.4", login: loginPacketIDs121, configuration: configurationPacketIDs121}, + {number: 770, name: "1.21.5", login: loginPacketIDs121, configuration: configurationPacketIDs121}, + {number: 771, name: "1.21.6", login: loginPacketIDs121, configuration: configurationPacketIDs121}, + {number: 772, name: "1.21.8", login: loginPacketIDs121, configuration: configurationPacketIDs121}, + {number: 773, name: "1.21.9", login: loginPacketIDs121, configuration: configurationPacketIDs121}, + {number: 774, name: "1.21.11", login: loginPacketIDs121, configuration: configurationPacketIDs121}, + {number: 775, name: "26.1", login: loginPacketIDs121, configuration: configurationPacketIDs121}, + {number: 776, name: "26.2", login: loginPacketIDs121, configuration: configurationPacketIDs121, loginFinishedSessionID: true}, + {number: 777, name: "26.3", login: loginPacketIDs121, configuration: configurationPacketIDs121, loginFinishedSessionID: true}, +} + +// latestProtocolVersion is the newest row. It is what the client advertises +// unless a version is configured, and what the server reports in its status +// response. +var latestProtocolVersion = protocolVersions[len(protocolVersions)-1] + +// protocolVersionByNumber finds a row. An unknown number is an error rather +// than a guess: a wrong packet id breaks the login in a way that looks like a +// network failure, so the configuration has to name a version the table knows. +func protocolVersionByNumber(number Varint) (protocolVersion, bool) { + for _, version := range protocolVersions { + if version.number == number { + return version, true + } + } + return protocolVersion{}, false +} + +// ValidateProtocolVersion checks a configured network protocol number. Zero is +// valid and selects the newest row. Configuration is validated when it is built, +// so a version that is not in the table fails before a connection is attempted. +func ValidateProtocolVersion(number uint32) error { + if number == 0 { + return nil + } + if _, ok := protocolVersionByNumber(Varint(number)); !ok { + return fmt.Errorf("unsupported protocol version %d (supported: %s)", number, protocolVersionRange()) + } + return nil +} + +// protocolVersionRange describes the supported versions for error messages. +func protocolVersionRange() string { + first, last := protocolVersions[0], protocolVersions[len(protocolVersions)-1] + return fmt.Sprintf("%d (%s) to %d (%s)", first.number, first.name, last.number, last.name) +} + +// isProtocolVersionReject recognises the Login Disconnect reasons vanilla sends +// when the client named another protocol version, so the cached detection can be +// dropped. +func isProtocolVersionReject(reason string) bool { + return strings.Contains(reason, "multiplayer.disconnect.incompatible") || + strings.Contains(reason, "multiplayer.disconnect.outdated_client") +} + +// loginRejectReason is the Login Disconnect reason a vanilla server sends for a +// protocol version it does not speak. Vanilla splits the message at 1.20.5 +// (754): older clients are told to update, newer ones that the server is +// incompatible. +func loginRejectReason(number Varint) string { + if number < 754 { + return fmt.Sprintf(`{"translate":"multiplayer.disconnect.outdated_client","with":[%q]}`, latestProtocolVersion.name) + } + return fmt.Sprintf(`{"translate":"multiplayer.disconnect.incompatible","with":[%q]}`, latestProtocolVersion.name) +} diff --git a/transport/internet/finalmask/xmc/protocol_table_test.go b/transport/internet/finalmask/xmc/protocol_table_test.go new file mode 100644 index 000000000..99e3f7444 --- /dev/null +++ b/transport/internet/finalmask/xmc/protocol_table_test.go @@ -0,0 +1,165 @@ +package xmc + +import ( + "strings" + "testing" +) + +// TestProtocolTablePinsRegistrationOrder pins every id XMC uses against the +// source it came from, so that changing a row is a conscious edit and not a +// side effect of a refactor: +// +// - 767..775: minecraft-data data/pc//protocol.json, keyed by the +// packet name in the same order LoginProtocols and ConfigurationProtocols +// register them; +// - 776..777: the official 26.2 and 26.3 jars. +func TestProtocolTablePinsRegistrationOrder(t *testing.T) { + wantLogin := loginPacketIDs{ + serverboundLoginStart: 0x00, + serverboundKey: 0x01, + serverboundCustomQueryAnswer: 0x02, + serverboundLoginAcknowledged: 0x03, + serverboundCookieResponse: 0x04, + + clientboundLoginDisconnect: 0x00, + clientboundHello: 0x01, + clientboundLoginFinished: 0x02, + clientboundLoginCompression: 0x03, + clientboundCustomQuery: 0x04, + clientboundCookieRequest: 0x05, + } + wantConfiguration := configurationPacketIDs{ + serverboundClientInformation: 0x00, + serverboundCookieResponse: 0x01, + serverboundCustomPayload: 0x02, + serverboundKeepAlive: 0x04, + serverboundPong: 0x05, + + clientboundCookieRequest: 0x00, + clientboundCustomPayload: 0x01, + clientboundDisconnect: 0x02, + clientboundKeepAlive: 0x04, + clientboundPing: 0x05, + } + + for _, version := range protocolVersions { + if version.login != wantLogin { + t.Fatalf("%s (%d): login ids = %+v, want %+v", version.name, version.number, version.login, wantLogin) + } + if version.configuration != wantConfiguration { + t.Fatalf("%s (%d): configuration ids = %+v, want %+v", version.name, version.number, version.configuration, wantConfiguration) + } + } +} + +// TestProtocolTableCoverage checks the table is a contiguous, ordered run of +// the releases XMC supports, and that the newest row is the default. +func TestProtocolTableCoverage(t *testing.T) { + if len(protocolVersions) == 0 { + t.Fatal("empty protocol table") + } + for i, version := range protocolVersions { + want := Varint(767 + i) + if version.number != want { + t.Fatalf("row %d is protocol %d, want %d", i, version.number, want) + } + if version.name == "" { + t.Fatalf("row %d (%d) has no release name", i, version.number) + } + if version.loginFinishedSessionID != (version.number >= 776) { + t.Fatalf("%s (%d): loginFinishedSessionID = %v", version.name, version.number, version.loginFinishedSessionID) + } + } + + if latestProtocolVersion.number != 777 || latestProtocolVersion.name != "26.3" { + t.Fatalf("latest row = %s (%d), want 26.3 (777)", latestProtocolVersion.name, latestProtocolVersion.number) + } + if !latestProtocolVersion.loginFinishedSessionID { + t.Fatal("26.3 must carry the Login Finished session id") + } + if _, ok := protocolVersionByNumber(776); !ok { + t.Fatal("26.2 row is missing") + } + if _, ok := protocolVersionByNumber(775); !ok { + t.Fatal("26.1 row is missing") + } +} + +func TestProtocolVersionByNumberRejectsUnknown(t *testing.T) { + for _, number := range []Varint{0, 1, 766, 778, 9999} { + if _, ok := protocolVersionByNumber(number); ok { + t.Fatalf("protocol %d should not be in the table", number) + } + } +} + +func TestProtocolVersionRange(t *testing.T) { + got := protocolVersionRange() + for _, want := range []string{"767 (1.21.1)", "777 (26.3)"} { + if !strings.Contains(got, want) { + t.Fatalf("range %q does not contain %q", got, want) + } + } +} + +// TestLoginRejectReason checks the vanilla split at 1.20.5 (754): older clients +// are told to update, newer ones that the server is incompatible. +func TestLoginRejectReason(t *testing.T) { + if got := loginRejectReason(700); !strings.Contains(got, "multiplayer.disconnect.outdated_client") { + t.Fatalf("old client reason = %s", got) + } + for _, number := range []Varint{754, 775, 778} { + got := loginRejectReason(number) + if !strings.Contains(got, "multiplayer.disconnect.incompatible") { + t.Fatalf("protocol %d reason = %s", number, got) + } + if !strings.Contains(got, `"with":["26.3"]`) { + t.Fatalf("protocol %d reason has no version argument: %s", number, got) + } + } +} + +// TestStatusResponse pins the status JSON shape a vanilla server builds: a +// collapsed literal description, player counts with an empty sample, and the +// version it speaks. +func TestStatusResponse(t *testing.T) { + got := statusResponse(latestProtocolVersion) + want := `{"description":"A Minecraft Server","players":{"max":20,"online":0,"sample":[]},"version":{"name":"26.3","protocol":777},"enforcesSecureChat":true}` + if got != want { + t.Fatalf("status = %s\nwant %s", got, want) + } + if got := statusResponse(protocolVersions[0]); !strings.Contains(got, `"version":{"name":"1.21.1","protocol":767}`) { + t.Fatalf("1.21.1 status = %s", got) + } +} + +func TestValidPlayerName(t *testing.T) { + for _, name := range []string{"Notch", "a", "Player_123", "Player.Name-1", strings.Repeat("a", 16)} { + if !validPlayerName(name) { + t.Fatalf("%q should be a valid 26.x player name", name) + } + } + // 26.x only rejects lengths above sixteen and bytes outside printable ASCII: + // spaces and the old "letters, digits, underscore" restriction are gone. + for _, name := range []string{strings.Repeat("a", 17), "name with space", "tab\tname", "high\x7f", "unicode\u00e9"} { + if validPlayerName(name) { + t.Fatalf("%q should be rejected", name) + } + } +} + +func TestGameVersion(t *testing.T) { + version, err := (&Config{}).gameVersion() + if err != nil || version.number != latestProtocolVersion.number { + t.Fatalf("default version = %v, %v", version.number, err) + } + + version, err = (&Config{ProtocolVersion: 775}).gameVersion() + if err != nil || version.number != 775 { + t.Fatalf("configured version = %v, %v", version.number, err) + } + + if _, err = (&Config{ProtocolVersion: 778}).gameVersion(); err == nil || !strings.Contains(err.Error(), "unsupported protocol version 778") { + t.Fatalf("unknown version error = %v", err) + } +} diff --git a/transport/internet/finalmask/xmc/server.go b/transport/internet/finalmask/xmc/server.go index 60cd3aa65..ef5ac2cf9 100644 --- a/transport/internet/finalmask/xmc/server.go +++ b/transport/internet/finalmask/xmc/server.go @@ -2,7 +2,6 @@ package xmc import ( "bufio" - "bytes" "context" "crypto/rand" "crypto/rsa" @@ -24,12 +23,22 @@ const ( // still missing, instead of making every login wait a fixed interval. yggdrasilVerifyFirstPoll = 10 * time.Millisecond yggdrasilVerifyMaxPoll = 200 * time.Millisecond + // maxPlayerNameLength is vanilla's Login Start limit (readUtf(16)). + maxPlayerNameLength = 16 ) var errYggdrasilNotJoined = errors.New("player did not join the minecraft session") -// Response by vanilla 26.1.2 server. -var statusResponse = `{"description":"A Minecraft Server","players":{"max":20,"online":0},"version":{"name":"26.1.2","protocol":775},"enforcesSecureChat":true}` +// serverSessionID is the connection session id that Login Finished carries from +// 26.2 on. Vanilla generates it once per server rather than per connection, so +// one value for the process has the same shape. +var serverSessionID = sync.OnceValues(func() (UUID, error) { + var sessionID UUID + if _, err := rand.Read(sessionID[:]); err != nil { + return UUID{}, fmt.Errorf("generate session id: %w", err) + } + return sessionID, nil +}) type serverState int @@ -45,6 +54,10 @@ type serverConn struct { state serverState + // protocol is the row selected from the client's handshake. Both ends have + // to use the same ids, and the client is the side that names the version. + protocol protocolVersion + handshakeLock sync.Mutex lifecycleMu sync.Mutex closed bool @@ -52,9 +65,11 @@ type serverConn struct { password string rsaPrivateKey *rsa.PrivateKey rsaPublicKey []byte + dataChannel string + paddingChannel string yggdrasil *yggdrasilVerifier paddingSchedule []paddingTurn - packet *packetStream + packet *tickStream deadlines *connectionDeadlines done chan struct{} @@ -75,10 +90,10 @@ func (c *serverConn) handshake() error { defer func() { _ = c.deadlines.endHandshake() }() var ( - protocolVersion Varint - serverAddress String - serverPort UnsignedShort - nextState Varint + protocolNumber Varint + serverAddress String + serverPort UnsignedShort + nextState Varint ) // handshake packet @@ -88,11 +103,11 @@ func (c *serverConn) handshake() error { return fmt.Errorf("read handshake packet: %w", err) } - if pkt.packetID != 0 { + if pkt.packetID != handshakeServerboundIntention { return fmt.Errorf("bad handshake packet id") } - err = pkt.readFields(&protocolVersion, &serverAddress, &serverPort, &nextState) + err = pkt.readFields(&protocolNumber, &serverAddress, &serverPort, &nextState) if err != nil { return fmt.Errorf("read handshake packet: %w", err) } @@ -110,14 +125,14 @@ func (c *serverConn) handshake() error { } switch pkt.packetID { - case 0: // Status Request + case statusServerboundRequest: // Status Request - err = writePacket(c.writer, 0, new(String(statusResponse))) + err = writePacket(c.writer, statusClientboundResponse, new(String(statusResponse(latestProtocolVersion)))) if err != nil { return fmt.Errorf("write status response: %w", err) } - case 1: // Ping + case statusServerboundPing: // Ping var payload Long err = pkt.readFields(&payload) @@ -125,7 +140,7 @@ func (c *serverConn) handshake() error { return fmt.Errorf("read ping packet: %w", err) } - err = writePacket(c.writer, 1, &payload) + err = writePacket(c.writer, statusClientboundPong, &payload) if err != nil { return fmt.Errorf("write ping response: %w", err) } @@ -136,167 +151,34 @@ func (c *serverConn) handshake() error { return fmt.Errorf("ping") - case 2: + case 2, 3: - // Login - - // login start - - pkt, err := readPacket(c.reader) - if err != nil { - return fmt.Errorf("read login start packet: %w", err) + // Login. A vanilla server starts the login protocol, checks the version + // against its own, and only then reads Login Start; TRANSFER shares the + // login but is only accepted when the server allows transfers, which the + // mask does not. + if nextState == 3 { + reason := `{"translate":"multiplayer.disconnect.transfers_disabled"}` + _ = writePacket(c.writer, latestProtocolVersion.login.clientboundLoginDisconnect, new(String(reason))) + return fmt.Errorf("transfers are disabled") } - if pkt.packetID != 0 { - return fmt.Errorf("bad login start packet id") + // The version picks the row, not the other way around: the ids are the + // registration order of the peer's own protocol, so the client decides. + // An unknown version is rejected with the same Login Disconnect a vanilla + // server sends for it. The disconnect id is taken from the newest row + // because no row matches, and no release has ever moved it. + protocol, known := protocolVersionByNumber(protocolNumber) + if !known { + reason := String(loginRejectReason(protocolNumber)) + _ = writePacket(c.writer, latestProtocolVersion.login.clientboundLoginDisconnect, &reason) + return fmt.Errorf("unsupported protocol version: %d", protocolNumber) } + c.protocol = protocol - var ( - username String - uuid UUID - ) - - err = pkt.readFields(&username, &uuid) - if err != nil { - return fmt.Errorf("read login start packet: %w", err) - } - profile, found := findProfile(c.profiles, string(username), uuid) - - // encrypt request - - var ( - serverId String = String("") - publicKey Bytes = Bytes(c.rsaPublicKey) - verifyToken Bytes = Bytes(make([]byte, 4)) - shouldAuthenticate Boolean = true - ) - - if _, err = rand.Read(verifyToken); err != nil { - return fmt.Errorf("generate verify token: %w", err) - } - - err = writePacket(c.writer, 0x01, &serverId, &publicKey, &verifyToken, &shouldAuthenticate) - if err != nil { - return fmt.Errorf("write encryption request: %w", err) - } - - // encrypt response - - var ( - encryptedSharedSecret Bytes - encryptedVerifyToken Bytes - - sharedSecret []byte - decryptedVerifyToken []byte - ) - - pkt, err = readPacket(c.reader) - if err != nil { - return fmt.Errorf("read encrypt response: %w", err) - } - - if pkt.packetID != 0x01 { - return fmt.Errorf("bad encrypt response packet id") - } - - err = pkt.readFields(&encryptedSharedSecret, &encryptedVerifyToken) - if err != nil { - return fmt.Errorf("read encrypt response: %w", err) - } - - sharedSecret, err = rsa.DecryptPKCS1v15(rand.Reader, c.rsaPrivateKey, encryptedSharedSecret) - if err != nil { - return fmt.Errorf("decrypt shared secret: %w", err) - } - if len(sharedSecret) != 16 { - return fmt.Errorf("bad shared secret length: %d", len(sharedSecret)) - } - - decryptedVerifyToken, err = rsa.DecryptPKCS1v15(rand.Reader, c.rsaPrivateKey, encryptedVerifyToken) - if err != nil { - return fmt.Errorf("decrypt verify token: %w", err) - } - - if len(decryptedVerifyToken) < 4 || !bytes.Equal(verifyToken, decryptedVerifyToken[:4]) { - return fmt.Errorf("verify token mismatch") - } - - c.reader, err = newCryptoReader(c.reader, sharedSecret) - if err != nil { - return fmt.Errorf("new crypto reader: %w", err) - } - - c.writer, err = newCryptoWriter(c.writer, sharedSecret) - if err != nil { - return fmt.Errorf("new crypto writer: %w", err) - } - - if c.yggdrasil != nil { - // Online-mode login: verify the player through the session server - // instead of the pre-shared password and the static profile list. - if !bytes.Equal(decryptedVerifyToken, verifyToken) { - return fmt.Errorf("verify token mismatch") - } - - serverID := minecraftServerID(string(serverId), sharedSecret, c.rsaPublicKey) - profile, err = c.verifyYggdrasilLogin(string(username), uuid, serverID) - if err != nil { - reason := `{"type":"translatable","translate":"multiplayer.disconnect.unverified_username"}` - if !errors.Is(err, errYggdrasilNotJoined) { - reason = `{"type":"translatable","translate":"multiplayer.disconnect.authservers_down"}` - } - if writeErr := writeDisconnectPacket(c.writer, reason); writeErr != nil { - return fmt.Errorf("write yggdrasil disconnect: %w", writeErr) - } - return fmt.Errorf("verify yggdrasil login: %w", err) - } - } else { - // verify password - receivedPassword := decryptedVerifyToken[4:] - - if subtle.ConstantTimeCompare(receivedPassword, []byte(c.password)) != 1 { - _ = writeDisconnectPacket(c.writer, `{"type":"translatable","translate":"multiplayer.disconnect.authservers_down"}`) - return fmt.Errorf("bad password") - } - if !found { - if err = writeDisconnectPacket(c.writer, `{"text":"You are not white-listed on this server!"}`); err != nil { - return fmt.Errorf("write unknown login profile disconnect: %w", err) - } - return fmt.Errorf("unknown login profile") - } - } - - if err = writeLoginSuccess(c.writer, profile); err != nil { - return fmt.Errorf("write login finished: %w", err) - } - - var loginAcknowledgedLength int - pkt, loginAcknowledgedLength, err = readPacketWithLength(c.reader) - if err != nil { - return fmt.Errorf("read login acknowledged: %w", err) - } - if err = validateLoginAcknowledgedPacket(pkt); err != nil { + if err = c.login(); err != nil { return err } - c.reader = newPaddingReader(c.reader, false) - if err = runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause); err != nil { - _ = c.Close() // Unblock the startup reader if writing failed. - return fmt.Errorf("run startup padding: %w", err) - } - - packet := newPacketStream(c.reader, c.writer, false) - c.lifecycleMu.Lock() - if c.closed { - c.lifecycleMu.Unlock() - packet.Stop() - return net.ErrClosed - } - c.packet = packet - c.reader = packet - c.writer = packet - c.state = serverStateProxy - c.lifecycleMu.Unlock() - return nil default: @@ -304,6 +186,222 @@ func (c *serverConn) handshake() error { } } +// login runs the login state once the protocol version is known. +func (c *serverConn) login() error { + // login start + + pkt, err := readPacket(c.reader) + if err != nil { + return fmt.Errorf("read login start packet: %w", err) + } + + if pkt.packetID != c.protocol.login.serverboundLoginStart { + return fmt.Errorf("bad login start packet id") + } + + var ( + username String + uuid UUID + ) + + err = pkt.readFields(&username, &uuid) + if err != nil { + return fmt.Errorf("read login start packet: %w", err) + } + if !validPlayerName(string(username)) { + return fmt.Errorf("invalid player name: %q", string(username)) + } + profile, found := findProfile(c.profiles, string(username), uuid) + + // encrypt request + + var ( + serverId String = String("") + publicKey Bytes = Bytes(c.rsaPublicKey) + verifyToken Bytes = Bytes(make([]byte, 4)) + shouldAuthenticate Boolean = true + ) + + if _, err = rand.Read(verifyToken); err != nil { + return fmt.Errorf("generate verify token: %w", err) + } + + err = writePacket(c.writer, c.protocol.login.clientboundHello, &serverId, &publicKey, &verifyToken, &shouldAuthenticate) + if err != nil { + return fmt.Errorf("write encryption request: %w", err) + } + + // encrypt response + + var ( + encryptedSharedSecret Bytes + encryptedVerifyToken Bytes + + sharedSecret []byte + decryptedVerifyToken []byte + ) + + pkt, err = readPacket(c.reader) + if err != nil { + return fmt.Errorf("read encrypt response: %w", err) + } + + if pkt.packetID != c.protocol.login.serverboundKey { + return fmt.Errorf("bad encrypt response packet id") + } + + err = pkt.readFields(&encryptedSharedSecret, &encryptedVerifyToken) + if err != nil { + return fmt.Errorf("read encrypt response: %w", err) + } + + // The order is vanilla's: handleKey runs ServerboundKeyPacket.isChallengeValid + // and turns a bad challenge into java.lang.IllegalStateException: Protocol + // error before it ever touches the secret key, so a bad challenge closes the + // connection unencrypted and a good one fails inside the CFB8 stream. That + // difference is drawn by vanilla too and the mask keeps it. The challenge is + // the 4 random bytes this server sent moments ago, so an oracle on it + // discloses nothing. + // + // The shared secret is the opposite case: it is the only secret on the wire, + // so it is decrypted with the session-key countermeasure and never branched + // on. See decryptSharedSecret. + decryptedVerifyToken, verifyTokenOK := decryptVerifyToken(c.rsaPrivateKey, encryptedVerifyToken) + if !verifyTokenOK || !challengesEqual(verifyToken, decryptedVerifyToken) { + return fmt.Errorf("verify token mismatch") + } + + sharedSecret, blockCipher, sharedSecretOK := c.decryptSharedSecret(encryptedSharedSecret) + if !sharedSecretOK { + return fmt.Errorf("decrypt shared secret") + } + + c.reader = newCryptoReaderWithBlock(c.reader, blockCipher, sharedSecret) + c.writer = newCryptoWriterWithBlock(c.writer, blockCipher, sharedSecret) + + // From here the connection is encrypted and every rejection is a Login + // Disconnect inside it, exactly like the rejections vanilla sends after a + // successful challenge. Nothing below branches on padding validity and the + // password comparison is constant time. A peer that did not send a valid + // secret cannot read this answer at all: it is encrypted under a random key + // the peer never saw. + var reason string + if c.yggdrasil != nil { + // Online-mode login: verify the player through the session server + // instead of the pre-shared password and the static profile list. + // Vanilla's client sends the bare challenge back, and this reports an + // unknown player to the client rather than the API outage a second + // session server round trip would guess at. + if len(decryptedVerifyToken) != len(verifyToken) { + return fmt.Errorf("verify token mismatch") + } + + serverID := minecraftServerID(string(serverId), sharedSecret, c.rsaPublicKey) + profile, err = c.verifyYggdrasilLogin(string(username), uuid, serverID) + if err != nil { + reason = `{"translate":"multiplayer.disconnect.unverified_username"}` + if !errors.Is(err, errYggdrasilNotJoined) { + reason = `{"translate":"multiplayer.disconnect.authservers_down"}` + } + } + } else { + // verify password + receivedPassword := decryptedVerifyToken[len(verifyToken):] + + if subtle.ConstantTimeCompare(receivedPassword, []byte(c.password)) != 1 { + // A wrong password is reported as an outage, the answer vanilla + // gives when the session check that would have authorised the + // player fails. Only a peer that already sent the right password can + // reach the profile check below, so the whitelist answer is never + // visible to a guesser. + reason = `{"translate":"multiplayer.disconnect.authservers_down"}` + } else if !found { + // The password is shared, the profile list is not: only a holder of + // the password can ever see this answer. + reason = `{"text":"You are not white-listed on this server!"}` + } + } + + if reason != "" { + if writeErr := writeDisconnectPacket(c.writer, c.protocol.login.clientboundLoginDisconnect, reason); writeErr != nil { + return fmt.Errorf("write login disconnect: %w", writeErr) + } + return fmt.Errorf("authentication rejected") + } + + // No Set Compression, which is the same wire as a vanilla server with + // network-compression-threshold=-1: the startup padding preset reproduces a + // login that ran without it, and the tunnel payloads are already compressed + // or encrypted by whoever produced them. The client still negotiates the + // compressed framing when the peer is a real server that enables it. + if err = writeLoginFinished(c.writer, c.protocol, profile); err != nil { + return fmt.Errorf("write login finished: %w", err) + } + + var loginAcknowledgedLength int + pkt, loginAcknowledgedLength, err = readPacketWithLength(c.reader) + if err != nil { + return fmt.Errorf("read login acknowledged: %w", err) + } + if err = validateLoginAcknowledgedPacket(pkt, c.protocol.login.serverboundLoginAcknowledged); err != nil { + return err + } + + return c.startProxy(loginAcknowledgedLength) +} + +// startProxy runs the startup padding and hands the connection to the tick +// stream. It is called once the login reached the configuration state. +func (c *serverConn) startProxy(loginAcknowledgedLength int) error { + c.reader = newPaddingReader(c.reader, false, c.paddingChannel, c.protocol.configuration) + if err := runPaddingSchedule(c.writer, false, loginAcknowledgedLength, c.paddingSchedule, c.paddingPause, c.paddingChannel, c.protocol.configuration); err != nil { + _ = c.Close() // Unblock the startup reader if writing failed. + return fmt.Errorf("run startup padding: %w", err) + } + + packet := newTickStream(c.reader, c.writer, false, c.protocol.configuration, c.dataChannel, c.paddingChannel) + c.lifecycleMu.Lock() + if c.closed { + c.lifecycleMu.Unlock() + packet.Stop() + return net.ErrClosed + } + c.packet = packet + c.reader = packet + c.writer = packet + c.state = serverStateProxy + c.lifecycleMu.Unlock() + + return nil +} + +// validPlayerName mirrors vanilla's Login Start check in 26.x: at most sixteen +// bytes, all printable ASCII. The older "letters, digits and underscore" +// restriction was dropped, so filtering it here would reject players a vanilla +// server accepts. +func validPlayerName(name string) bool { + if len(name) > maxPlayerNameLength { + return false + } + for i := 0; i < len(name); i++ { + if name[i] <= 32 || name[i] >= 127 { + return false + } + } + return true +} + +// statusResponse is the status JSON a vanilla server of this version builds: +// a collapsed literal description, the player counts with an empty sample, and +// the version the server speaks. +func statusResponse(version protocolVersion) string { + return fmt.Sprintf( + `{"description":"A Minecraft Server","players":{"max":20,"online":0,"sample":[]},"version":{"name":%q,"protocol":%d},"enforcesSecureChat":true}`, + version.name, + version.number, + ) +} + func (c *serverConn) verifyYggdrasilLogin(username string, uuid UUID, serverID string) (loginProfile, error) { ctx, cancel := context.WithTimeout(context.Background(), yggdrasilVerifyTimeout) defer cancel() @@ -348,8 +446,8 @@ func (c *serverConn) verifyYggdrasilLogin(username string, uuid UUID, serverID s } } -func validateLoginAcknowledgedPacket(pkt *mcPacket) error { - if pkt.packetID != 0x03 { +func validateLoginAcknowledgedPacket(pkt *mcPacket, packetID int) error { + if pkt.packetID != packetID { return fmt.Errorf("bad login acknowledged packet id: %d", pkt.packetID) } if len(pkt.data) != 0 { @@ -383,6 +481,10 @@ func (c *serverConn) Close() error { c.lifecycleMu.Unlock() c.closeOnce.Do(func() { close(c.done) }) if packet != nil { + // Write returns once data is queued for the next tick, so a graceful + // close has to flush the last tick instead of dropping it. + _ = c.c.SetWriteDeadline(time.Now().Add(time.Second)) + _ = packet.Flush() packet.Stop() } return c.c.Close() @@ -413,7 +515,7 @@ func (c *serverConn) SetWriteDeadline(t time.Time) error { return c.deadlines.setWriteDeadline(t) } -func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier) (*serverConn, error) { +func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPrivateKeyDER []byte, rsaPublicKey []byte, paddingSchedule []paddingTurn, yggdrasil *yggdrasilVerifier, dataChannel, paddingChannel string) (*serverConn, error) { if len(profiles) == 0 && yggdrasil == nil { return nil, fmt.Errorf("empty profiles") } @@ -437,6 +539,8 @@ func wrapConnServer(c net.Conn, profiles []loginProfile, password string, rsaPri password: password, rsaPrivateKey: rsaPrivateKey, rsaPublicKey: rsaPublicKey, + dataChannel: dataChannel, + paddingChannel: paddingChannel, yggdrasil: yggdrasil, paddingSchedule: paddingSchedule, deadlines: newConnectionDeadlines(c), diff --git a/transport/internet/finalmask/xmc/stream.go b/transport/internet/finalmask/xmc/stream.go index e44746949..66b807123 100644 --- a/transport/internet/finalmask/xmc/stream.go +++ b/transport/internet/finalmask/xmc/stream.go @@ -17,9 +17,9 @@ type cryptoStream struct { } func newCryptoReader(r io.Reader, sharedSecret []byte) (*cryptoStream, error) { - blockCipher, err := aes.NewCipher(sharedSecret) + blockCipher, err := newAESCipher(sharedSecret) if err != nil { - return nil, fmt.Errorf("new aes cipher: %w", err) + return nil, err } stream := newCFB8Decrypt(blockCipher, sharedSecret) @@ -27,6 +27,27 @@ func newCryptoReader(r io.Reader, sharedSecret []byte) (*cryptoStream, error) { return &cryptoStream{stream: stream, r: r}, nil } +func newAESCipher(sharedSecret []byte) (cipher.Block, error) { + blockCipher, err := aes.NewCipher(sharedSecret) + if err != nil { + return nil, fmt.Errorf("new aes cipher: %w", err) + } + return blockCipher, nil +} + +// newCryptoReaderWithBlock is newCryptoReader for a caller that already holds +// the cipher block, so the key stays in the caller's hands until it installs the +// stream. +func newCryptoReaderWithBlock(r io.Reader, blockCipher cipher.Block, sharedSecret []byte) *cryptoStream { + return &cryptoStream{stream: newCFB8Decrypt(blockCipher, sharedSecret), r: r} +} + +// newCryptoWriterWithBlock is newCryptoWriter for a caller that already holds +// the cipher block. +func newCryptoWriterWithBlock(w io.Writer, blockCipher cipher.Block, sharedSecret []byte) *cryptoStream { + return &cryptoStream{stream: newCFB8Encrypt(blockCipher, sharedSecret), w: w} +} + func (c *cryptoStream) Read(b []byte) (int, error) { if c.r == nil { panic("read on a write-only crypto stream") @@ -50,9 +71,9 @@ func (c *cryptoStream) Read(b []byte) (int, error) { } func newCryptoWriter(w io.Writer, sharedSecret []byte) (*cryptoStream, error) { - blockCipher, err := aes.NewCipher(sharedSecret) + blockCipher, err := newAESCipher(sharedSecret) if err != nil { - return nil, fmt.Errorf("new aes cipher: %w", err) + return nil, err } stream := newCFB8Encrypt(blockCipher, sharedSecret) diff --git a/transport/internet/finalmask/xmc/tick_stream_test.go b/transport/internet/finalmask/xmc/tick_stream_test.go new file mode 100644 index 000000000..7932e0e07 --- /dev/null +++ b/transport/internet/finalmask/xmc/tick_stream_test.go @@ -0,0 +1,209 @@ +package xmc + +import ( + "bytes" + "io" + "sync" + "testing" + "time" +) + +// tickTestWriter records every batch the tick stream writes to the network. +type tickTestWriter struct { + mu sync.Mutex + writes [][]byte +} + +func (w *tickTestWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + w.writes = append(w.writes, append([]byte(nil), p...)) + return len(p), nil +} + +func (w *tickTestWriter) snapshot() [][]byte { + w.mu.Lock() + defer w.mu.Unlock() + return append([][]byte(nil), w.writes...) +} + +func readTickBatch(t *testing.T, batch []byte) []*mcPacket { + t.Helper() + r := bytes.NewReader(batch) + var packets []*mcPacket + for r.Len() > 0 { + packet, err := readPacket(r) + if err != nil { + t.Fatalf("parse tick batch: %v", err) + } + packets = append(packets, packet) + } + return packets +} + +// tickPacketChannelAndPayload splits one custom payload into its channel name +// and the raw payload bytes that follow it. +func tickPacketChannelAndPayload(t *testing.T, packet *mcPacket) (string, []byte) { + t.Helper() + r := bytes.NewReader(packet.data) + var channel String + if err := channel.readFrom(r); err != nil { + t.Fatalf("read tick packet channel: %v", err) + } + payload, err := io.ReadAll(r) + if err != nil { + t.Fatalf("read tick packet payload: %v", err) + } + return string(channel), payload +} + +func collectTickData(t *testing.T, batches [][]byte) (data []byte, dataPackets, padding int) { + t.Helper() + for _, batch := range batches { + for _, packet := range readTickBatch(t, batch) { + channel, payload := tickPacketChannelAndPayload(t, packet) + switch channel { + case DefaultDataChannel: + data = append(data, payload...) + dataPackets++ + case DefaultPaddingChannel: + padding++ + } + } + } + return data, dataPackets, padding +} + +// TestTickStreamIdleCadence pins the 20 Hz shape: an idle connection still +// emits one small padding frame per tick in both directions. +func TestTickStreamIdleCadence(t *testing.T) { + writer := &tickTestWriter{} + stream := newTickStream(nil, writer, true, configurationPacketIDs121, DefaultDataChannel, DefaultPaddingChannel) + defer stream.Stop() + + time.Sleep(180 * time.Millisecond) + stream.Stop() + // Wait for an in-flight tick so the recorded batches are complete. + _ = stream.Flush() + + batches := writer.snapshot() + if len(batches) < 2 || len(batches) > 6 { + t.Fatalf("got %d tick batches in 180ms, want about 3", len(batches)) + } + for i, batch := range batches { + packets := readTickBatch(t, batch) + if len(packets) != 1 { + t.Fatalf("idle tick %d wrote %d packets, want 1", i, len(packets)) + } + if packets[0].packetID != configurationPacketIDs121.serverboundCustomPayload { + t.Fatalf("idle tick %d packet id = %d", i, packets[0].packetID) + } + channel, _ := tickPacketChannelAndPayload(t, packets[0]) + if channel != DefaultPaddingChannel { + t.Fatalf("idle tick %d channel = %q", i, channel) + } + } +} + +// TestTickStreamSendsQueuedDataInOneTick checks that proxy data is queued and +// then emitted as one per-tick batch, split at maxPacketData boundaries. +func TestTickStreamSendsQueuedDataInOneTick(t *testing.T) { + writer := &tickTestWriter{} + stream := newTickStream(nil, writer, true, configurationPacketIDs121, DefaultDataChannel, DefaultPaddingChannel) + defer stream.Stop() + + payload := bytes.Repeat([]byte("0123456789abcdef"), 4096) + if _, err := stream.Write(payload); err != nil { + t.Fatal(err) + } + + deadline := time.Now().Add(time.Second) + var ( + data []byte + dataPackets int + padding int + ) + for time.Now().Before(deadline) { + batches := writer.snapshot() + if len(batches) > 0 { + data, dataPackets, padding = collectTickData(t, batches) + if len(data) >= len(payload) { + break + } + } + time.Sleep(5 * time.Millisecond) + } + + if !bytes.Equal(data, payload) { + t.Fatalf("got %d payload bytes, want %d", len(data), len(payload)) + } + wantPackets := (len(payload) + maxPacketData - 1) / maxPacketData + if dataPackets != wantPackets { + t.Fatalf("got %d data packets, want %d", dataPackets, wantPackets) + } + if padding < 1 { + t.Fatal("the tick that carried data did not carry a padding frame") + } +} + +// TestTickStreamFlushWritesQueuedDataImmediately covers graceful close: data +// already accepted by Write must not wait for the next tick. +func TestTickStreamFlushWritesQueuedDataImmediately(t *testing.T) { + writer := &tickTestWriter{} + stream := newTickStream(nil, writer, true, configurationPacketIDs121, DefaultDataChannel, DefaultPaddingChannel) + defer stream.Stop() + + payload := []byte("flush me") + if _, err := stream.Write(payload); err != nil { + t.Fatal(err) + } + if err := stream.Flush(); err != nil { + t.Fatal(err) + } + + data, _, _ := collectTickData(t, writer.snapshot()) + if !bytes.Equal(data, payload) { + t.Fatalf("flush delivered %q, want %q", data, payload) + } +} + +// TestPingPongEncoding pins the configuration ping/pong form: the id is a plain +// 32-bit integer, not a varint. Vanilla rejected a varint pong with "Failed to +// decode packet 'serverbound/minecraft:pong'", which is why this is tested +// separately from the rest of the stream. +func TestPingPongEncoding(t *testing.T) { + packetIDs := configurationPacketIDs121 + + var wire bytes.Buffer + pingID := Int(0x01020304) + if err := writePacket(&wire, packetIDs.clientboundPing, &pingID); err != nil { + t.Fatal(err) + } + packet, err := readPacket(&wire) + if err != nil { + t.Fatal(err) + } + var received Int + if err := packet.readFields(&received); err != nil { + t.Fatalf("read ping id as int: %v", err) + } + if received != pingID { + t.Fatalf("ping id = %#x, want %#x", received, pingID) + } + + var out bytes.Buffer + stream := &tickStream{writer: &out, isClient: true, packetIDs: packetIDs} + if err := stream.writePong(received); err != nil { + t.Fatal(err) + } + answer, err := readPacket(&out) + if err != nil { + t.Fatal(err) + } + if answer.packetID != packetIDs.serverboundPong { + t.Fatalf("pong packet id = 0x%02x", answer.packetID) + } + if !bytes.Equal(answer.data, []byte{1, 2, 3, 4}) { + t.Fatalf("pong body = %x, want 01020304", answer.data) + } +} diff --git a/transport/internet/finalmask/xmc/yggdrasil.go b/transport/internet/finalmask/xmc/yggdrasil.go index 5eda95965..b60a3fa5c 100644 --- a/transport/internet/finalmask/xmc/yggdrasil.go +++ b/transport/internet/finalmask/xmc/yggdrasil.go @@ -468,6 +468,14 @@ type yggdrasilAuth struct { keyMu sync.Mutex signatureKey *rsa.PublicKey + + // loginMu serializes the login exchange of one account, from Login Start to + // the peer's Login Finished. The session server keeps one server id per + // profile, so only the most recent /join answers hasJoined; a second login + // that started while the first server was still polling would overwrite + // that session and the first server would reject it with + // unverified_username. + loginMu sync.Mutex } func newYggdrasilAuth(config *yggdrasilConfig) *yggdrasilAuth { diff --git a/transport/internet/finalmask/xmc/yggdrasil_test.go b/transport/internet/finalmask/xmc/yggdrasil_test.go index 29ed5f767..93c3c434e 100644 --- a/transport/internet/finalmask/xmc/yggdrasil_test.go +++ b/transport/internet/finalmask/xmc/yggdrasil_test.go @@ -58,6 +58,15 @@ type fakeYggdrasil struct { boundProfile string joined map[string]string // serverId -> profile name + + // latestServerID is the server id of the most recent join. A real session + // server keeps one id per profile, so with singleSession set only that id + // answers hasJoined. + latestServerID string + singleSession bool + // hasJoinedDelay widens the window in which a concurrent join can replace + // the session under test. + hasJoinedDelay time.Duration } func writeFakeYggdrasilJSON(w http.ResponseWriter, status int, body string) { @@ -124,15 +133,30 @@ func newFakeYggdrasilHandler(state *fakeYggdrasil) http.Handler { state.joinCalls++ state.boundProfile = request.SelectedProfile state.joined[request.ServerID] = state.profile.Name + state.latestServerID = request.ServerID w.WriteHeader(http.StatusNoContent) }) mux.HandleFunc(prefix+"/sessionserver/session/minecraft/hasJoined", func(w http.ResponseWriter, r *http.Request) { + serverID := r.URL.Query().Get("serverId") + username := r.URL.Query().Get("username") + + state.mu.Lock() + delay := state.hasJoinedDelay + state.mu.Unlock() + if delay > 0 { + time.Sleep(delay) + } + state.mu.Lock() defer state.mu.Unlock() - name, found := state.joined[r.URL.Query().Get("serverId")] - if !found || name != r.URL.Query().Get("username") { + if state.singleSession && state.latestServerID != serverID { + w.WriteHeader(http.StatusNoContent) + return + } + name, found := state.joined[serverID] + if !found || name != username { w.WriteHeader(http.StatusNoContent) return } @@ -358,11 +382,14 @@ func TestHandshakeWithYggdrasil(t *testing.T) { t.Errorf("new verifier: %v", err) return } - server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier) + server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel) if err != nil { t.Errorf("wrap server: %v", err) return } + // Write queues the payload for the next tick, so Close has to flush it + // before the raw connection is torn down. + defer server.Close() buf := make([]byte, 1024) n, err := server.Read(buf) @@ -387,7 +414,7 @@ func TestHandshakeWithYggdrasil(t *testing.T) { // The client intentionally has no pinned server key: Yggdrasil mode accepts // the key sent by the server and binds it through the session hash. - client, err := newClientConn(rawClient, nil, password, nil, "localhost", nil, newTestYggdrasilAuth(t, api, "SkinUser")) + client, err := newClientConn(rawClient, latestProtocolVersion, nil, password, nil, "localhost", nil, newTestYggdrasilAuth(t, api, "SkinUser"), DefaultDataChannel, DefaultPaddingChannel) if err != nil { t.Fatalf("new client: %v", err) } @@ -421,6 +448,128 @@ func TestHandshakeWithYggdrasil(t *testing.T) { } } +// TestYggdrasilConcurrentLoginsSerialized checks that one account never runs two +// logins at once. The session server keeps a single server id per profile, so a +// concurrent login would overwrite the session of a server that is still polling +// hasJoined, and that server would answer unverified_username. The fake API here +// behaves like the real one (only the most recent /join answers hasJoined) and +// adds latency to make the overwrite window wide. +func TestYggdrasilConcurrentLoginsSerialized(t *testing.T) { + state, api := newFakeYggdrasilServer(t) + state.singleSession = true + state.hasJoinedDelay = 25 * time.Millisecond + + const logins = 4 + + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("listen: %v", err) + } + defer ln.Close() + + password := "yggdrasil-rsa-seed" + privateKey, publicKey := deriveTestRSAKey(t, password) + + var servers sync.WaitGroup + servers.Add(logins) + go func() { + for i := 0; i < logins; i++ { + rawConn, err := ln.Accept() + if err != nil { + t.Errorf("accept: %v", err) + servers.Done() + continue + } + go func(conn net.Conn) { + defer servers.Done() + defer conn.Close() + + verifier, err := newYggdrasilVerifier(api) + if err != nil { + t.Errorf("new verifier: %v", err) + return + } + server, err := wrapConnServer(conn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel) + if err != nil { + t.Errorf("wrap server: %v", err) + return + } + defer server.Close() + + buf := make([]byte, 64) + n, err := server.Read(buf) + if err != nil { + t.Errorf("server read: %v", err) + return + } + if !bytes.Equal(buf[:n], []byte("ping")) { + t.Errorf("unexpected payload: %q", buf[:n]) + return + } + if _, err := server.Write([]byte("ok")); err != nil { + t.Errorf("server write: %v", err) + } + }(rawConn) + } + }() + + // One auth value for all connections, like one Xray process and one account. + auth := newTestYggdrasilAuth(t, api, "SkinUser") + + var clients sync.WaitGroup + errs := make(chan error, logins) + for i := 0; i < logins; i++ { + clients.Add(1) + go func() { + defer clients.Done() + + rawConn, err := net.Dial("tcp", ln.Addr().String()) + if err != nil { + errs <- fmt.Errorf("dial: %w", err) + return + } + defer rawConn.Close() + + client, err := newClientConn(rawConn, latestProtocolVersion, nil, "", nil, "localhost", nil, auth, DefaultDataChannel, DefaultPaddingChannel) + if err != nil { + errs <- fmt.Errorf("new client: %w", err) + return + } + defer client.Close() + + if _, err := client.Write([]byte("ping")); err != nil { + errs <- fmt.Errorf("client write: %w", err) + return + } + reply := make([]byte, 2) + if err := client.SetReadDeadline(time.Now().Add(30 * time.Second)); err != nil { + errs <- err + return + } + if _, err := io.ReadFull(client, reply); err != nil { + errs <- fmt.Errorf("client read: %w", err) + return + } + if string(reply) != "ok" { + errs <- fmt.Errorf("unexpected reply: %q", reply) + } + }() + } + + clients.Wait() + servers.Wait() + close(errs) + for err := range errs { + t.Error(err) + } + + state.mu.Lock() + defer state.mu.Unlock() + if state.joinCalls != logins { + t.Errorf("join calls = %d, want %d", state.joinCalls, logins) + } +} + func TestYggdrasilVerifiesTexturesSignature(t *testing.T) { state, api := newFakeYggdrasilServer(t) auth := newTestYggdrasilAuth(t, api, "SkinUser") @@ -554,7 +703,7 @@ func TestYggdrasilLoginFailure(t *testing.T) { if err != nil { return } - server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier) + server, err := wrapConnServer(rawConn, nil, password, privateKey, publicKey, nil, verifier, DefaultDataChannel, DefaultPaddingChannel) if err != nil { return } @@ -568,7 +717,7 @@ func TestYggdrasilLoginFailure(t *testing.T) { } defer rawClient.Close() - client, err := newClientConn(rawClient, nil, password, publicKey, "localhost", nil, newTestYggdrasilAuth(t, api, "")) + client, err := newClientConn(rawClient, latestProtocolVersion, nil, password, publicKey, "localhost", nil, newTestYggdrasilAuth(t, api, ""), DefaultDataChannel, DefaultPaddingChannel) if err != nil { t.Fatal(err) }