Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -85,81 +85,7 @@ private void debug(String message) {
@Override
public boolean channelRead(Object packet) throws Exception {
if (ClassNames.HANDSHAKE_PACKET.isInstance(packet)) {
if (ProxyUtils.isBungeeData()) {
// Server has bungee enabled and expects to receive player data in hostname of handshake packet.
// See https://hub.spigotmc.org/stash/projects/SPIGOT/repos/spigot/browse/CraftBukkit-Patches/0031-BungeeCord-Support.patch#70
String hostname = getCastedValue(packet, ClassNames.HANDSHAKE_HOST);

// Strip any pre-existing BungeeCord data from hostname (moxy may have added it)
// BungeeCord data is separated by \0, so get just the virtual host part
if (hostname.contains("\0")) {
hostname = hostname.split("\0")[0];
debug("Stripped pre-existing BungeeCord data from hostname");
}

String newHostname = createBungeeForwardingAddress(hostname);

if (ClassNames.IS_PRE_1_20_2) {
// 1.20.1 and below - can modify final field directly
setValue(packet, ClassNames.HANDSHAKE_HOST, newHostname);
} else {
// 1.20.2+ - final fields cannot be modified, create new packet instead
try {
Object[] components = new Object[]{
getCastedValue(packet, ClassNames.HANDSHAKE_PROTOCOL),
newHostname, // new hostname
getCastedValue(packet, ClassNames.HANDSHAKE_PORT),
getCastedValue(packet, ClassNames.HANDSHAKE_INTENTION)
};
Object newPacket = ClassNames.HANDSHAKE_PACKET_CONSTRUCTOR.newInstance(components);
// Replace the packet in the pipeline
ctx.fireChannelRead(newPacket);
if (!SpigotPlugin.isProtocolSupport()) {
removeSelf();
}
return false; // Don't pass the original packet
} catch (Exception e) {
throw new IllegalStateException("Failed to create new Handshake packet", e);
}
}

if (!SpigotPlugin.isProtocolSupport()) { // if we don't check this the player would be kicked with "unexpected hello packet"
removeSelf();
}
return true;
} else {
// BungeeCord mode is disabled, but moxy might have sent BungeeCord data anyway
// Strip it to prevent Paper from rejecting with "Unknown data in login hostname"
String hostname = getCastedValue(packet, ClassNames.HANDSHAKE_HOST);
if (hostname.contains("\0")) {
hostname = hostname.split("\0")[0];
debug("BungeeCord mode disabled but hostname contained forwarding data, stripped it");

if (ClassNames.IS_PRE_1_20_2) {
setValue(packet, ClassNames.HANDSHAKE_HOST, hostname);
} else {
// 1.20.2+ - final fields cannot be modified, create new packet instead
try {
Object[] components = new Object[]{
getCastedValue(packet, ClassNames.HANDSHAKE_PROTOCOL),
hostname, // stripped hostname
getCastedValue(packet, ClassNames.HANDSHAKE_PORT),
getCastedValue(packet, ClassNames.HANDSHAKE_INTENTION)
};
Object newPacket = ClassNames.HANDSHAKE_PACKET_CONSTRUCTOR.newInstance(components);
ctx.fireChannelRead(newPacket);
if (!SpigotPlugin.isProtocolSupport()) {
removeSelf();
}
return false; // Don't pass the original packet
} catch (Exception e) {
throw new IllegalStateException("Failed to create new Handshake packet", e);
}
}
}
}
// When BungeeCord mode is disabled, don't remove self - we need to handle LOGIN_START_PACKET
return true; // next is LOGIN_START_PACKET
return handleHandshake(new ReflectiveHandshake(packet));
}
if (ClassNames.LOGIN_START_PACKET.isInstance(packet)) {
debug("Processing LOGIN_START_PACKET for " + logPlayer());
Expand Down Expand Up @@ -247,6 +173,123 @@ public boolean channelRead(Object packet) throws Exception {
return true;
}

/** Handshake handling with the connector's live server state. */
boolean handleHandshake(HandshakeView handshake) {
return handleHandshake(handshake, ProxyUtils.isBungeeData(), SpigotPlugin.isProtocolSupport());
}

/**
* Decides what happens to the client's handshake - and to the connector's own pipeline slot.
*
* <p><b>BungeeCord forwarding enabled</b> (the server expects the player data in the hostname,
* see the CraftBukkit BungeeCord patch): the player data is injected into the hostname and, the
* server now owning the login, the connector leaves the pipeline - unless ProtocolSupport is
* installed, which needs it to stay or the player is kicked with "unexpected hello packet".
*
* <p><b>BungeeCord forwarding disabled</b>: forwarding data in the hostname (data a proxy added,
* or a client marker such as Forge's {@code \0FORGE}) is stripped, because the server would
* otherwise reject the hostname ("Unknown data in login hostname"). The connector MUST stay in
* the pipeline on this path: Connect owns the login here and injects the fake offline login
* cycle when {@code LOGIN_START} arrives - the packet AFTER the handshake. A connector that
* removed itself here never saw {@code LOGIN_START}, so no profile was injected and an
* online-mode server was free to start its own encryption handshake into the tunnel, which the
* edge cannot answer: the backend session died as {@code backend_connect} ~20 ms after the
* tunnel opened and the player fell back to the hub (connect-spigot 0.15.18, Paper 26.3,
* case t_117be469).
*
* @return true when the original packet may continue downstream
*/
boolean handleHandshake(HandshakeView handshake, boolean bungeeForwarding, boolean protocolSupport) {
String hostname = handshake.hostname();
if (bungeeForwarding) {
String virtualHost = stripForwardingData(hostname);
if (!virtualHost.equals(hostname)) {
debug("Stripped pre-existing BungeeCord data from hostname");
}
boolean rewrittenInPlace = handshake.replaceHostname(createBungeeForwardingAddress(virtualHost));
if (!protocolSupport) {
handshake.stopAfterHandshake();
}
return rewrittenInPlace;
}
String strippedHostname = stripForwardingData(hostname);
if (strippedHostname.equals(hostname)) {
return true; // next is LOGIN_START_PACKET
}
debug("BungeeCord mode disabled but hostname contained forwarding data, stripped it");
// Keep handling: the fake login cycle that serves this session runs on LOGIN_START_PACKET.
return handshake.replaceHostname(strippedHostname);
}

/** Drops forwarding data (everything after the first {@code \0}) from a handshake hostname. */
static String stripForwardingData(String hostname) {
int end = hostname.indexOf('\0');
return end == -1 ? hostname : hostname.substring(0, end);
}

/**
* The handshake packet surface the connector needs: its hostname, a way to rewrite it, and the
* connector's own pipeline slot. Production reads it reflectively from the server's packet
* ({@link ClassNames} needs a live server), which is why it is an interface at all.
*/
interface HandshakeView {
String hostname();

/**
* Sends the handshake downstream with the given hostname.
*
* @return true when the packet was rewritten in place, so the original continues downstream;
* false when a rebuilt packet was fired and the original must be dropped
*/
boolean replaceHostname(String hostname);

/** Removes the connector from the pipeline: this session no longer needs it. */
void stopAfterHandshake();
}

/** Adapts the reflected server handshake packet to {@link HandshakeView}. */
private final class ReflectiveHandshake implements HandshakeView {
private final Object packet;

private ReflectiveHandshake(Object packet) {
this.packet = packet;
}

@Override
public String hostname() {
return getCastedValue(packet, ClassNames.HANDSHAKE_HOST);
}

@Override
public boolean replaceHostname(String hostname) {
if (ClassNames.IS_PRE_1_20_2) {
// 1.20.1 and below - can modify final field directly
setValue(packet, ClassNames.HANDSHAKE_HOST, hostname);
return true;
}
// 1.20.2+ - final fields cannot be modified, create new packet instead
try {
Object[] components = new Object[]{
getCastedValue(packet, ClassNames.HANDSHAKE_PROTOCOL),
hostname, // new hostname
getCastedValue(packet, ClassNames.HANDSHAKE_PORT),
getCastedValue(packet, ClassNames.HANDSHAKE_INTENTION)
};
Object newPacket = ClassNames.HANDSHAKE_PACKET_CONSTRUCTOR.newInstance(components);
// Replace the packet in the pipeline
ctx.fireChannelRead(newPacket);
return false; // Don't pass the original packet
} catch (Exception e) {
throw new IllegalStateException("Failed to create new Handshake packet", e);
}
}

@Override
public void stopAfterHandshake() {
removeSelf();
}
}

/**
* Paper's post-1.20.4 fake login cycle, as the connector drives it.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
package com.minekube.connect.addon.data;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import com.minekube.connect.api.logger.ConnectLogger;
import com.minekube.connect.api.player.ConnectPlayer;
import com.minekube.connect.api.player.GameProfile;
import com.minekube.connect.config.ConnectConfig;
import com.minekube.connect.network.netty.LocalSession;
import io.netty.channel.embedded.EmbeddedChannel;
import java.net.InetSocketAddress;
import java.util.List;
import java.util.UUID;
import org.junit.jupiter.api.Test;

/**
* Guards the one handshake branch that rewrites the client's hostname and also decides whether the
* connector keeps its pipeline slot.
*
* <p>Defect reproduced end to end against connect-spigot 0.15.18 (Paper 26.3, online-mode=true,
* endpoint {@code offlineModeHeader: false}, case t_117be469): a modded client's handshake carries a
* {@code \0FORGE} marker, the connector strips it and then removed itself, so the fake offline login
* that Connect injects on {@code LOGIN_START} never ran. Paper (still owning an unverified login)
* started its own encryption handshake into the tunnel; the edge cannot answer that, so the backend
* session ended {@code backend_connect} 21.67 ms after the tunnel opened and the player was dropped
* into the browser hub. The same marker join completes on the same stack when the connector keeps
* handling {@code LOGIN_START}, and it already completed on the pre-fix jar with
* {@code online-mode=false} - which is exactly the mode where Paper never asks for encryption and
* therefore never needs the injection.
*
* <p>These tests drive the production {@code handleHandshake} decision, so both the hostname the
* server receives and the connector's pipeline decision are under test.
*/
class SpigotHandshakeStripTest {
private static final String ENDPOINT = "motomc.play.minekube.net";
private static final String FORGE_MARKER = "\0FORGE";
private static final String PLAYER = "R6vibin";
private static final UUID PLAYER_ID = UUID.fromString("5933d395-f771-4fe9-8a6f-14f34bcb7aab");

@Test
void keepsTheConnectorInstalledWhenItStripsAForwardingMarker() {
Fixture fixture = new Fixture(ENDPOINT + FORGE_MARKER);

boolean passOriginalDownstream = fixture.handler.handleHandshake(fixture.handshake, false, false);

assertFalse(passOriginalDownstream,
"the marked handshake must be replaced, not passed on to the server");
assertEquals(ENDPOINT, fixture.handshake.replacedHostname,
"the server must receive the hostname without the client's marker");
assertFalse(fixture.handshake.stopped,
"the connector must stay installed: its fake login cycle runs on LOGIN_START, and"
+ " removing it here hands an online-mode server an unverified login"
+ " (the 0.15.18 backend_connect teardown)");
}

@Test
void keepsHandlingAnUnmarkedHandshakeAndPassesItThrough() {
Fixture fixture = new Fixture(ENDPOINT);

boolean passOriginalDownstream = fixture.handler.handleHandshake(fixture.handshake, false, false);

assertTrue(passOriginalDownstream, "a clean handshake needs no rewrite");
assertNull(fixture.handshake.replacedHostname, "a clean handshake must not be replaced");
assertFalse(fixture.handshake.stopped);
}

@Test
void injectsBungeeForwardingDataAndLeavesThePipeline() {
Fixture fixture = new Fixture(PLAYER + "." + ENDPOINT + FORGE_MARKER);

boolean passOriginalDownstream = fixture.handler.handleHandshake(fixture.handshake, true, false);

assertFalse(passOriginalDownstream, "the rebuilt packet replaced the original");
String forwarded = fixture.handshake.replacedHostname;
assertTrue(forwarded.startsWith(PLAYER + "." + ENDPOINT + "\0"), forwarded);
assertTrue(forwarded.contains(PLAYER_ID.toString().replace("-", "")), forwarded);
assertTrue(fixture.handshake.stopped,
"in BungeeCord forwarding mode the server owns the login, so the connector leaves");
}

@Test
void staysForProtocolSupportWhenBungeeForwardingDataIsInjected() {
Fixture fixture = new Fixture(ENDPOINT + FORGE_MARKER);

fixture.handler.handleHandshake(fixture.handshake, true, true);

assertFalse(fixture.handshake.stopped,
"ProtocolSupport needs the connector to stay, or the player is kicked with"
+ " \"unexpected hello packet\"");
}

@Test
void stripForwardingDataDropsOnlyWhatFollowsTheFirstNull() {
assertEquals(ENDPOINT, SpigotDataHandler.stripForwardingData(ENDPOINT + FORGE_MARKER));
assertEquals(ENDPOINT, SpigotDataHandler.stripForwardingData(ENDPOINT + "\0" + "1.2.3.4\0abc\0[]"));
assertEquals(ENDPOINT, SpigotDataHandler.stripForwardingData(ENDPOINT));
}

/** A handler with the session state the handshake branch reads, and a recording handshake. */
private static final class Fixture {
private final ConnectConfig config = mock(ConnectConfig.class);
private final StubHandshake handshake;
private final SpigotDataHandler handler;
private final EmbeddedChannel channel;

private Fixture(String hostname) {
LocalSession.Context session = mock(LocalSession.Context.class);
ConnectPlayer player = mock(ConnectPlayer.class);
lenient().when(config.isDebug()).thenReturn(false);
lenient().when(session.getPlayer()).thenReturn(player);
lenient().when(session.getSpoofedAddress())
.thenReturn(InetSocketAddress.createUnresolved("93.201.72.37", 0));
lenient().when(player.getUniqueId()).thenReturn(PLAYER_ID);
lenient().when(player.getUsername()).thenReturn(PLAYER);
when(player.getGameProfile()).thenReturn(new GameProfile(PLAYER, PLAYER_ID, List.of()));

this.handshake = new StubHandshake(hostname);
this.handler = new SpigotDataHandler(session, "packet_handler", config,
mock(ConnectLogger.class), null);
this.channel = new EmbeddedChannel(handler);
}
}

private static final class StubHandshake implements SpigotDataHandler.HandshakeView {
private final String hostname;
private String replacedHostname;
private boolean stopped;

private StubHandshake(String hostname) {
this.hostname = hostname;
}

@Override
public String hostname() {
return hostname;
}

@Override
public boolean replaceHostname(String hostname) {
this.replacedHostname = hostname;
return false; // 1.20.2+: a rebuilt packet was fired, the original is dropped
}

@Override
public void stopAfterHandshake() {
this.stopped = true;
}
}
}
Loading