[SSH] Fix ProxyConnector when buffer longer than the proxy message If the peer's SSH identity is received in the same TCP message as the final successful proxy protocol message, we need to process the remaining data through the normal SSH message handling. For HTTP CONNECT, identify the end of the headers (two CR-LF pairs) and if there is any data following handle it as SSH protocol data. Limit the length of the headers to 32kB. For SOCKS, simply handle anything remaining in the buffer as SSH protocol data. Bug: jgit-270 Change-Id: I911b696ac4f4b20b86cbfe93beca745e8cda93a1
diff --git a/org.eclipse.jgit.ssh.apache.test/tst/org/eclipse/jgit/internal/transport/sshd/proxy/AccumulatorTest.java b/org.eclipse.jgit.ssh.apache.test/tst/org/eclipse/jgit/internal/transport/sshd/proxy/AccumulatorTest.java new file mode 100644 index 0000000..5f69265 --- /dev/null +++ b/org.eclipse.jgit.ssh.apache.test/tst/org/eclipse/jgit/internal/transport/sshd/proxy/AccumulatorTest.java
@@ -0,0 +1,93 @@ +/* + * 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.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +import java.nio.charset.StandardCharsets; + +import org.apache.sshd.common.util.buffer.ByteArrayBuffer; +import org.junit.Test; + +/** + * Basic tests for {@link Accumulator}. + */ +public class AccumulatorTest { + + private static final byte[] END = { '\r', '\n', '\r', '\n' }; + + @Test + public void normalInput() throws Exception { + byte[] data = "Complete line\r\nHeader:foo\r\nOther:bar\r\n\r\nSomething else\r\n\r\nanother line" + .getBytes(StandardCharsets.US_ASCII); + Accumulator acc = new Accumulator(100, END, "Headers too long"); + assertTrue(acc.accumulate(new ByteArrayBuffer(data))); + String headers = new String(acc.getData(), StandardCharsets.US_ASCII); + String body = new String(acc.getRest(), StandardCharsets.US_ASCII); + assertEquals("Something else\r\n\r\nanother line", body); + assertArrayEquals(data, + (headers + body).getBytes(StandardCharsets.US_ASCII)); + } + + @Test + public void noBody() throws Exception { + byte[] data = "Complete line\r\nHeader:foo\r\nOther:bar\r\n\r\n" + .getBytes(StandardCharsets.US_ASCII); + Accumulator acc = new Accumulator(100, END, "Headers too long"); + assertTrue(acc.accumulate(new ByteArrayBuffer(data))); + String headers = new String(acc.getData(), StandardCharsets.US_ASCII); + String body = new String(acc.getRest(), StandardCharsets.US_ASCII); + assertEquals("", body); + assertArrayEquals(data, headers.getBytes(StandardCharsets.US_ASCII)); + } + + @Test + public void fragmentedInput() throws Exception { + byte[] data = "Complete line\r\nHeader:foo\r\nOther:bar\r\n\r\nSomething else\r\n\r\nanother line" + .getBytes(StandardCharsets.US_ASCII); + Accumulator acc = new Accumulator(100, END, "Headers too long"); + for (int i = 0; i < data.length; i++) { + if (i < 39) { + assertFalse("Failed false at " + i, + acc.accumulate(new ByteArrayBuffer(data, i, 1))); + } else { + assertTrue("Failed true at " + i, + acc.accumulate(new ByteArrayBuffer(data, i, 1))); + } + } + String headers = new String(acc.getData(), StandardCharsets.US_ASCII); + String body = new String(acc.getRest(), StandardCharsets.US_ASCII); + assertEquals("Something else\r\n\r\nanother line", body); + assertArrayEquals(data, + (headers + body).getBytes(StandardCharsets.US_ASCII)); + } + + @Test + public void limitExceeded() throws Exception { + byte[] data = new byte[11]; + Accumulator acc = new Accumulator(10, END, "Headers too long"); + assertThrows(Exception.class, + () -> acc.accumulate(new ByteArrayBuffer(data))); + } + + @Test + public void limitExceededFragmented() throws Exception { + byte[] data = new byte[8]; + Accumulator acc = new Accumulator(10, END, "Headers too long"); + assertFalse(acc.accumulate(new ByteArrayBuffer(data))); + assertThrows(Exception.class, + () -> acc.accumulate(new ByteArrayBuffer(data))); + } + +}
diff --git a/org.eclipse.jgit.ssh.apache/resources/org/eclipse/jgit/internal/transport/sshd/SshdText.properties b/org.eclipse.jgit.ssh.apache/resources/org/eclipse/jgit/internal/transport/sshd/SshdText.properties index 768b52b..f894dd0 100644 --- a/org.eclipse.jgit.ssh.apache/resources/org/eclipse/jgit/internal/transport/sshd/SshdText.properties +++ b/org.eclipse.jgit.ssh.apache/resources/org/eclipse/jgit/internal/transport/sshd/SshdText.properties
@@ -81,7 +81,9 @@ pkcs11Warning=WARNING: {0} proxyCannotAuthenticate=Cannot authenticate to proxy {0} proxyHttpFailure=HTTP Proxy connection to {0} failed with code {1}: {2} +proxyHttpHeadersTooLong=HTTP headers too long proxyHttpInvalidUserName=HTTP proxy connection {0} with invalid user name; must not contain colons: {1} +proxyHttpMessageTooLong=HTTP message too long (more than {0} bytes): {1} proxyHttpUnexpectedReply=Unexpected HTTP proxy response from {0}: {1} proxyHttpUnspecifiedFailureReason=unspecified reason proxyJumpAbort=ProxyJump chain too long at {0}
diff --git a/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/SshdText.java b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/SshdText.java index 1d699b2..7d08f8f 100644 --- a/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/SshdText.java +++ b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/SshdText.java
@@ -103,7 +103,9 @@ public static SshdText get() { /***/ public String pkcs11Warning; /***/ public String proxyCannotAuthenticate; /***/ public String proxyHttpFailure; + /***/ public String proxyHttpHeadersTooLong; /***/ public String proxyHttpInvalidUserName; + /***/ public String proxyHttpMessageTooLong; /***/ public String proxyHttpUnexpectedReply; /***/ public String proxyHttpUnspecifiedFailureReason; /***/ public String proxyJumpAbort;
diff --git a/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/AbstractClientProxyConnector.java b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/AbstractClientProxyConnector.java index a05d641..a7dd278 100644 --- a/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/AbstractClientProxyConnector.java +++ b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/AbstractClientProxyConnector.java
@@ -1,5 +1,5 @@ /* - * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch> and others + * Copyright (C) 2018, 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 @@ -18,6 +18,8 @@ import java.util.concurrent.atomic.AtomicReference; import org.apache.sshd.client.session.ClientSession; +import org.apache.sshd.common.util.Readable; +import org.apache.sshd.common.util.buffer.Buffer; import org.eclipse.jgit.annotations.NonNull; import org.eclipse.jgit.internal.transport.sshd.JGitClientSession; @@ -27,6 +29,11 @@ public abstract class AbstractClientProxyConnector implements StatefulProxyConnector { + @FunctionalInterface + private interface ThrowingConsumer<T> { + void consume(T arg) throws Exception; + } + private static final long DEFAULT_PROXY_TIMEOUT_NANOS = TimeUnit.SECONDS .toNanos(30L); @@ -43,6 +50,8 @@ public abstract class AbstractClientProxyConnector private long lastProxyOperationTime = 0L; + private ThrowingConsumer<Readable> trailingDataHandler; + /** The ultimate remote address to connect to. */ protected final InetSocketAddress remoteAddress; @@ -94,6 +103,7 @@ protected void init(ClientSession session) { if (session instanceof JGitClientSession) { JGitClientSession s = (JGitClientSession) session; unregister.set(() -> s.setProxyHandler(null)); + trailingDataHandler = s::messageReceived; s.setProxyHandler(this); } else { // Internal error, no translation @@ -135,10 +145,14 @@ protected void adjustTimeout() { * * @param success * whether the connector terminated successfully. + * @param lastData + * if {@code success == true}, a buffer that may contain the + * remaining data received (can be {@code null} if no further + * data was received) * @throws Exception * if starting ssh fails */ - protected void setDone(boolean success) throws Exception { + protected void setDone(boolean success, Buffer lastData) throws Exception { List<Callable<Void>> buffered; Runnable unset = unregister.getAndSet(null); if (unset != null) { @@ -149,9 +163,15 @@ protected void setDone(boolean success) throws Exception { buffered = bufferedCommands; bufferedCommands = null; } - if (success && buffered != null) { - for (Callable<Void> starter : buffered) { - starter.call(); + if (success) { + if (lastData != null && lastData.available() > 0) { + lastData.compact(); + trailingDataHandler.consume(lastData); + } + if (buffered != null) { + for (Callable<Void> starter : buffered) { + starter.call(); + } } } }
diff --git a/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/Accumulator.java b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/Accumulator.java new file mode 100644 index 0000000..8653867 --- /dev/null +++ b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/Accumulator.java
@@ -0,0 +1,126 @@ +/* + * 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 java.io.IOException; +import java.text.MessageFormat; +import java.util.Arrays; + +import org.apache.sshd.common.util.Readable; +import org.apache.sshd.common.util.buffer.ByteArrayBuffer; +import org.eclipse.jgit.internal.transport.sshd.SshdText; + +/** + * Accumulates bytes until the first occurrence of a given byte sequence. + */ +class Accumulator { + + private final int limit; + + private final byte[] endOfData; + + private final String errorMessage; + + private ByteArrayBuffer buf = new ByteArrayBuffer(); + + private int split = -1; + + Accumulator(int limit, byte[] endOfData, String errorMessage) { + if (endOfData == null || endOfData.length == 0) { + throw new IllegalArgumentException("end marker must be non-empty"); //$NON-NLS-1$ + } + if (limit < endOfData.length) { + throw new IllegalArgumentException( + "limit must be >= length of end marker"); //$NON-NLS-1$ + } + this.endOfData = endOfData.clone(); + this.limit = limit; + this.errorMessage = errorMessage; + } + + /** + * Accumulates the given input and returns whether the end marker was found. + * + * @param input + * to accumulate + * @return {@code true} if the data accumulated so far contains the end + * marker, {@code false} otherwise + * @throws IOException + * if the limit is exceeded + */ + boolean accumulate(Readable input) throws IOException { + int lastCheck = buf.available(); + buf.putBuffer(input); + int len = buf.available(); + if (split < 0 && len > lastCheck && len >= endOfData.length) { + // Avoid re-checking already checked parts of the buffer. If the + // last check didn't find the end marker up to lastCheck, we don't + // have to start over again at the beginning: it suffices to double + // check the last N-1 bytes (plus then the new bytes) if N is + // endOfData.length. + int from = (lastCheck >= endOfData.length) + ? lastCheck + 1 - endOfData.length + : buf.rpos(); + split = indexOf(buf.array(), from, buf.rpos() + len - from, + endOfData); + if (split >= 0) { + return true; + } + } + if (len > limit) { + if (split >= 0) { + // Usage error; no translation + throw new IOException( + "Limit exceeded after marker was found at index " //$NON-NLS-1$ + + split + "; limit = " + limit); //$NON-NLS-1$ + } + throw new IOException( + MessageFormat.format(SshdText.get().proxyHttpMessageTooLong, + Integer.valueOf(limit), errorMessage)); + } + return split >= 0; + } + + byte[] getData() { + if (split < 0) { + throw new IllegalStateException("Data not yet determined"); //$NON-NLS-1$ + } + return Arrays.copyOfRange(buf.array(), buf.rpos(), + split + endOfData.length); + } + + byte[] getRest() { + if (split < 0) { + throw new IllegalStateException( + "Data not yet determined, so rest still unknown"); //$NON-NLS-1$ + } + return Arrays.copyOfRange(buf.array(), split + endOfData.length, + buf.wpos()); + } + + void clear() { + buf = new ByteArrayBuffer(); + split = -1; + } + + private static int indexOf(byte[] data, int from, int len, byte[] needle) { + int to = from + len - needle.length; + for (int i = from; i <= to; i++) { + int j = 0; + for (int k = i; j < needle.length && data[k] == needle[j]; k++) { + j++; + } + if (j == needle.length) { + return i; + } + } + return -1; + } +}
diff --git a/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/HttpClientConnector.java b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/HttpClientConnector.java index b7deb29..315bee3 100644 --- a/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/HttpClientConnector.java +++ b/org.eclipse.jgit.ssh.apache/src/org/eclipse/jgit/internal/transport/sshd/proxy/HttpClientConnector.java
@@ -1,5 +1,5 @@ /* - * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch> and others + * Copyright (C) 2018, 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 @@ -44,6 +44,12 @@ public class HttpClientConnector extends AbstractClientProxyConnector { private static final String HTTP_HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization:"; //$NON-NLS-1$ + /** + * Maximum allowed length of the HTTP reply (status line + headers, + * including the final CRLF). + */ + private static final int MAX_REPLY_LENGTH = 32 * 1024; + private HttpAuthenticationHandler basic; private HttpAuthenticationHandler negotiate; @@ -56,6 +62,8 @@ public class HttpClientConnector extends AbstractClientProxyConnector { private boolean ongoing; + private Accumulator data; + /** * Creates a new {@link HttpClientConnector}. The connector supports * anonymous proxy connections as well as Basic and Negotiate @@ -96,6 +104,9 @@ public HttpClientConnector(@NonNull InetSocketAddress proxyAddress, availableAuthentications.add(negotiate); availableAuthentications.add(basic); clientAuthentications = availableAuthentications.iterator(); + data = new Accumulator(MAX_REPLY_LENGTH, + new byte[] { '\r', '\n', '\r', '\n' }, + SshdText.get().proxyHttpHeadersTooLong); } private void close() { @@ -132,9 +143,9 @@ public void sendClientProxyMetadata(ClientSession sshSession) } private void send(StringBuilder msg, IoSession session) throws Exception { - byte[] data = eol(msg).toString().getBytes(US_ASCII); - Buffer buffer = new ByteArrayBuffer(data.length, false); - buffer.putRawBytes(data); + byte[] toSend = eol(msg).toString().getBytes(US_ASCII); + Buffer buffer = new ByteArrayBuffer(toSend.length, false); + buffer.putRawBytes(toSend); session.writeBuffer(buffer).verify(getTimeout()); } @@ -161,12 +172,22 @@ private StringBuilder eol(StringBuilder msg) { public void messageReceived(IoSession session, Readable buffer) throws Exception { try { - int length = buffer.available(); - byte[] data = new byte[length]; - buffer.getRawBytes(data, 0, length); - String[] reply = new String(data, US_ASCII) - .split("\r\n"); //$NON-NLS-1$ - handleMessage(session, Arrays.asList(reply)); + if (!data.accumulate(buffer)) { + // Need more input + return; + } + byte[] headers = data.getData(); + byte[] body = data.getRest(); + data.clear(); + Buffer rest = null; + if (body.length > 0) { + rest = new ByteArrayBuffer(body); + } + String[] reply = new String(headers, US_ASCII).split("\r\n"); //$NON-NLS-1$ + boolean isDone = handleMessage(session, Arrays.asList(reply)); + if (isDone) { + setDone(true, rest); + } } catch (Exception e) { if (authenticator != null) { authenticator.close(); @@ -174,7 +195,7 @@ public void messageReceived(IoSession session, Readable buffer) } ongoing = false; try { - setDone(false); + setDone(false, null); } catch (Exception inner) { e.addSuppressed(inner); } @@ -182,7 +203,7 @@ public void messageReceived(IoSession session, Readable buffer) } } - private void handleMessage(IoSession session, List<String> reply) + private boolean handleMessage(IoSession session, List<String> reply) throws Exception { if (reply.isEmpty() || reply.get(0).isEmpty()) { throw new IOException( @@ -204,8 +225,7 @@ private void handleMessage(IoSession session, List<String> reply) } authenticator = null; ongoing = false; - setDone(true); - break; + return true; case HttpURLConnection.HTTP_PROXY_AUTH: List<AuthenticationChallenge> challenges = HttpParser .getAuthenticationHeaders(reply, @@ -223,7 +243,7 @@ private void handleMessage(IoSession session, List<String> reply) proxyAddress)); } send(authenticate(connect(), token), session); - break; + return false; default: throw new IOException(format(SshdText.get().proxyHttpFailure, proxyAddress, Integer.toString(status.getResultCode()),
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 bb227bb..3c3a82a 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
@@ -1,5 +1,5 @@ /* - * Copyright (C) 2018, Thomas Wolf <thomas.wolf@paranor.ch> and others + * Copyright (C) 2018, 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 @@ -367,7 +367,7 @@ private void establishConnection(Buffer data) throws Exception { switch (reply) { case SOCKS_REPLY_SUCCESS: state = ProtocolState.CONNECTED; - setDone(true); + setDone(true, data); return; case SOCKS_REPLY_FAILURE: throw new IOException(format( @@ -422,7 +422,7 @@ public void messageReceived(IoSession session, Readable buffer) authenticator = null; } try { - setDone(false); + setDone(false, null); } catch (Exception inner) { e.addSuppressed(inner); }