[SSH] Fix Socks5ClientConnector

Skip the full proxy reply in the success case; only return the data
after the full reply to the SSH session. If the reply is split over
multiple messages accumulate data until we have the full reply.

Bug: jgit-317
Change-Id: I0a728a4f0183591385ab42efe828ade48cc36c35
Also-by: t2itto
diff --git a/org.eclipse.jgit.ssh.apache.test/tst/org/eclipse/jgit/internal/transport/sshd/proxy/Socks5ProxyConnectorTest.java b/org.eclipse.jgit.ssh.apache.test/tst/org/eclipse/jgit/internal/transport/sshd/proxy/Socks5ProxyConnectorTest.java
new file mode 100644
index 0000000..4d8c8e7
--- /dev/null
+++ b/org.eclipse.jgit.ssh.apache.test/tst/org/eclipse/jgit/internal/transport/sshd/proxy/Socks5ProxyConnectorTest.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2026, Thomas Wolf <twolf@apache.org> and others
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Distribution License v. 1.0 which is available at
+ * https://www.eclipse.org/org/documents/edl-v10.php.
+ *
+ * SPDX-License-Identifier: BSD-3-Clause
+ */
+package org.eclipse.jgit.internal.transport.sshd.proxy;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
+import org.junit.Test;
+
+/**
+ * Basic tests for accumulating the SOCKS connection reply.
+ */
+public class Socks5ProxyConnectorTest {
+
+	@Test
+	public void splitConnectionReply() throws Exception {
+		byte[] chunk1 = new byte[] { 5 }; // Socks version
+		byte[] chunk2 = new byte[] { 0 /* Success */, 0 };
+		byte[] chunk3 = new byte[] { 1 /* IPv4 */, 1, 2, 3 };
+		byte[] chunk4 = new byte[] { 4, 0, 100, (byte) 'S', (byte) 'S',
+				(byte) 'H', (byte) '-', (byte) '2', (byte) '.', (byte) '0',
+				(byte) '-', (byte) 'X', (byte) '\n' };
+		InetSocketAddress unused = new InetSocketAddress(
+				InetAddress.getLocalHost(), 2000);
+		AtomicReference<Buffer> rest = new AtomicReference<>();
+		AtomicBoolean isDone = new AtomicBoolean();
+		Socks5ClientConnector connector = new Socks5ClientConnector(unused,
+				unused) {
+
+			@Override
+			protected void setDone(boolean success, Buffer lastData)
+					throws Exception {
+				isDone.set(success);
+				rest.set(lastData);
+			}
+		};
+		connector.receiveConnectReply(new ByteArrayBuffer(chunk1));
+		assertFalse(isDone.get());
+		assertNull(rest.get());
+		connector.receiveConnectReply(new ByteArrayBuffer(chunk2));
+		assertFalse(isDone.get());
+		assertNull(rest.get());
+		connector.receiveConnectReply(new ByteArrayBuffer(chunk3));
+		assertFalse(isDone.get());
+		assertNull(rest.get());
+		connector.receiveConnectReply(new ByteArrayBuffer(chunk4));
+		assertTrue(isDone.get());
+		Buffer data = rest.get();
+		assertNotNull(data);
+		String ident = new String(data.array(), data.rpos(), data.available(),
+				StandardCharsets.US_ASCII);
+		assertEquals("SSH-2.0-X\n", ident);
+	}
+
+}
diff --git a/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/Socks5ClientConnector.java b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/Socks5ClientConnector.java
index 3c3a82a..9c8bbf1 100644
--- a/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/Socks5ClientConnector.java
+++ b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/Socks5ClientConnector.java
@@ -145,22 +145,7 @@ public void handleMessage(Socks5ClientConnector connector,
 			@Override
 			public void handleMessage(Socks5ClientConnector connector,
 					IoSession session, Buffer data) throws Exception {
-				// Special case: when GSS-API authentication completes, the
-				// client moves into CONNECTING as soon as the GSS context is
-				// established and sends the connect request. This is per RFC
-				// 1961. But for the server, RFC 1961 says it _should_ send an
-				// empty token even if none generated when its server side
-				// context is established. That means we may actually get an
-				// empty token here. That message is 4 bytes long (and has
-				// content 0x01, 0x01, 0x00, 0x00). We simply skip this message
-				// if we get it here. If the server for whatever reason sends
-				// back a "GSS failed" message (it shouldn't, at this point)
-				// it will be two bytes 0x01 0xFF, which will fail the version
-				// check.
-				if (data.available() != 4) {
-					connector.versionCheck(data.getByte());
-					connector.establishConnection(data);
-				}
+				connector.receiveConnectReply(data);
 			}
 		},
 
@@ -186,6 +171,13 @@ public void handleMessage(Socks5ClientConnector connector,
 
 	private byte[] authenticationProposals;
 
+	// Part of the connect reply received so far, while it is incomplete
+	private Buffer pendingReply;
+
+	// True while an empty GSS-API token may still precede the connect reply
+	// (only after GSS-API authentication, RFC 1961)
+	private boolean emptyGssTokenPossible;
+
 	/**
 	 * Creates a new {@link Socks5ClientConnector}. The connector supports
 	 * anonymous connections as well as username-password or Kerberos5 (GSS-API)
@@ -309,6 +301,7 @@ private void doPasswordAuth(IoSession session) throws Exception {
 	}
 
 	private void doGssApiAuth(IoSession session) throws Exception {
+		emptyGssTokenPossible = true;
 		authenticator = new SocksGssApiAuthentication();
 		session.addCloseFutureListener(f -> close());
 		startAuth(session);
@@ -362,10 +355,119 @@ private void authStep(IoSession session, Buffer input) throws Exception {
 		}
 	}
 
+	// Accumulates the connect reply until it is complete, then hands only the
+	// data following it (typically the server's SSH identification) to the
+	// SSH session.
+	//
+	// Package-visible for a unit test.
+	void receiveConnectReply(Buffer data) throws Exception {
+		Buffer reply = data;
+		if (pendingReply != null) {
+			pendingReply.putBuffer(data);
+			reply = pendingReply;
+		}
+		if (emptyGssTokenPossible && reply.available() > 0) {
+			int pos = reply.rpos();
+			if (reply.rawByte(pos) == 1) {
+				if (reply.available() < 4) {
+					keepReply(reply);
+					return;
+				}
+				// Special case: when GSS-API authentication completes, the
+				// client moves into CONNECTING as soon as the GSS context is
+				// established and sends the connect request. This is per RFC
+				// 1961. But for the server, RFC 1961 says it _should_ send an
+				// empty token even if none generated when its server side
+				// context is established. That means we may actually get an
+				// empty token here. That message is 4 bytes long (and has
+				// content 0x01, 0x01, 0x00, 0x00). We simply skip this message
+				// if we get it here. If the server for whatever reason sends
+				// back a "GSS failed" message (it shouldn't, at this point)
+				// it will be two bytes 0x01 0xFF, which will fail the version
+				// check.
+				if (reply.rawByte(pos + 1) == 1 && reply.rawByte(pos + 2) == 0
+						&& reply.rawByte(pos + 3) == 0) {
+					reply.rpos(pos + 4);
+				}
+			}
+			emptyGssTokenPossible = false;
+		}
+		if (reply.available() == 0) {
+			pendingReply = null;
+			return;
+		}
+		versionCheck(reply.rawByte(reply.rpos()));
+		if (reply.available() >= 2
+				&& reply.rawByte(reply.rpos() + 1) != SOCKS_REPLY_SUCCESS) {
+			// Fail at once; don't wait for the rest of a failure reply
+			pendingReply = null;
+			reply.getByte();
+			establishConnection(reply);
+			return;
+		}
+		int length = getReplyLength(reply);
+		if (length < 0 || reply.available() < length) {
+			keepReply(reply);
+			return;
+		}
+		pendingReply = null;
+		reply.getByte();
+		establishConnection(reply);
+	}
+
+	private void keepReply(Buffer reply) {
+		if (pendingReply == null) {
+			pendingReply = new ByteArrayBuffer(reply.available() + 64, false);
+			pendingReply.putBuffer(reply);
+		}
+	}
+
+	// Length of the whole connect reply, or -1 if not enough of it has been
+	// received yet to tell
+	private int getReplyLength(Buffer reply) throws IOException {
+		if (reply.available() < 4) {
+			return -1;
+		}
+		int pos = reply.rpos();
+		byte type = reply.rawByte(pos + 3);
+		switch (type) {
+		case SOCKS_ADDRESS_IPv4:
+			return 4 + 4 + 2;
+		case SOCKS_ADDRESS_IPv6:
+			return 4 + 16 + 2;
+		case SOCKS_ADDRESS_FQDN:
+			if (reply.available() < 5) {
+				return -1;
+			}
+			return 4 + 1 + (reply.rawByte(pos + 4) & 0xFF) + 2;
+		default:
+			// Internal error, no translation.
+			throw new IOException(format(
+					"Unexpected address type {0} in SOCKS connect reply from {1}", //$NON-NLS-1$
+					Integer.toString(type & 0xFF), proxyAddress));
+		}
+	}
+
+	// Skips RSV, ATYP, BND.ADDR and BND.PORT of a complete connect reply
+	private static void skipBoundAddress(Buffer data) {
+		data.getByte(); // RSV
+		byte type = data.getByte();
+		int length;
+		if (type == SOCKS_ADDRESS_IPv4) {
+			length = 4;
+		} else if (type == SOCKS_ADDRESS_IPv6) {
+			length = 16;
+		} else {
+			length = data.getUByte();
+		}
+		data.rpos(data.rpos() + length + 2);
+	}
+
 	private void establishConnection(Buffer data) throws Exception {
 		byte reply = data.getByte();
 		switch (reply) {
 		case SOCKS_REPLY_SUCCESS:
+			skipBoundAddress(data);
 			state = ProtocolState.CONNECTED;
 			setDone(true, data);
 			return;
@@ -417,6 +519,7 @@ public void messageReceived(IoSession session, Readable buffer)
 			state.handleMessage(this, session, data);
 		} catch (Exception e) {
 			state = ProtocolState.FAILED;
+			pendingReply = null;
 			if (authenticator != null) {
 				authenticator.close();
 				authenticator = null;