You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by tw...@apache.org on 2025/04/21 15:41:56 UTC
(mina-sshd) 01/02: GH-729: client-side proxy support
This is an automated email from the ASF dual-hosted git repository.
twolf pushed a commit to branch dev_3.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git
commit 158636318d6c27948b5183d3a7ec37c428ae9142
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Mon Apr 14 18:03:46 2025 +0200
GH-729: client-side proxy support
Bring over the client-side proxy support from JGit and adapt it for use
as a ClientProxyFilter in the filter chain of an AbstractClientSession.
Includes integration tests for HTTP or SOCKS proxies. Also test using a
dynamic port forwarding, and fix the SOCKS listener in Apache MINA sshd.
Also change Sshd1033Test to use ephemeral ports instead of fixed ports.
---
CHANGES.md | 1 +
docs/client-setup.md | 49 +-
.../java/org/apache/sshd/client/ClientBuilder.java | 13 +
.../java/org/apache/sshd/client/SshClient.java | 33 +-
.../sshd/client/auth/keyboard/UserInteraction.java | 20 +-
.../sshd/client/proxy/DefaultProxyDataFactory.java | 83 +++
.../org/apache/sshd/client/proxy/ProxyData.java | 107 ++++
.../apache/sshd/client/proxy/ProxyDataFactory.java | 36 ++
.../sshd/client/session/AbstractClientSession.java | 18 +
.../client/session/filter/ClientProxyFilter.java | 169 +++++++
.../proxy/AbstractAuthenticationHandler.java | 59 +++
.../session/proxy/AbstractProxyConnector.java | 116 +++++
.../session/proxy/AuthenticationChallenge.java | 92 ++++
.../session/proxy/AuthenticationHandler.java | 86 ++++
.../client/session/proxy/BasicAuthentication.java | 120 +++++
.../client/session/proxy/GssApiAuthentication.java | 109 ++++
.../client/session/proxy/GssApiMechanisms.java | 192 +++++++
.../sshd/client/session/proxy/HttpParser.java | 336 +++++++++++++
.../client/session/proxy/HttpProxyConnector.java | 351 +++++++++++++
.../client/session/proxy/Socks5ProxyConnector.java | 559 +++++++++++++++++++++
.../sshd/client/session/proxy/StatusLine.java | 71 +++
.../apache/sshd/common/forward/SocksConstants.java | 88 ++++
.../org/apache/sshd/common/forward/SocksProxy.java | 124 +++--
.../sshd/common/session/filters/IdentFilter.java | 21 +-
.../session/filters/PacketLoggingFilter.java | 7 +-
.../sshd/common/session/filters/kex/KexFilter.java | 2 +-
.../session/filters/kex/KexOutputHandler.java | 11 +-
.../org/apache/sshd/core/CoreModuleProperties.java | 2 +-
.../sshd/client/ProxyHttpAuthIntegrationTest.java | 162 ++++++
.../sshd/client/ProxyHttpIntegrationTest.java | 108 ++++
.../client/{ProxyTest.java => ProxyJumpTest.java} | 4 +-
.../sshd/client/ProxySocksAuthIntegrationTest.java | 160 ++++++
.../sshd/client/ProxySocksIntegrationTest.java | 105 ++++
.../org/apache/sshd/client/ProxySocksTest.java | 140 ++++++
.../apache/sshd/common/forward/Sshd1033Test.java | 12 +-
.../org/apache/sshd/client/tinyproxy-auth.conf | 2 +
.../org/apache/sshd/client/tinyproxy.conf | 2 +
sshd-mina/pom.xml | 2 +
sshd-netty/pom.xml | 1 +
39 files changed, 3505 insertions(+), 68 deletions(-)
diff --git a/CHANGES.md b/CHANGES.md
index eb8414f50..2df9169b6 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -19,3 +19,4 @@ Version 3 includes all the features and bug fixes of version 2, including the [l
* Random padding on SSH packets as suggested by [RFC 4253, section 6](https://datatracker.ietf.org/doc/html/rfc4253#section-6).
* New event callback `SessionListener.sessionStarting()`. See the [filter documentation](./docs/technical/filters.md). `SessionListener.sessionEstablished()` was removed; it was called from the constructor of `AbstractSession` at a time when the object was not yet fully initialized.
* [GH-728](https://github.com/apache/mina-sshd/issues/728) New method `ClientSession.getHostConfigEntry()` to get the `HostConfigEntry` for the session.
+* [GH-729](https://github.com/apache/mina-sshd/issues/729) Support for client-side SOCKS5 or HTTP CONNECT proxies. See the [documentation](./docs/client-setup.md#proxies)
diff --git a/docs/client-setup.md b/docs/client-setup.md
index 0b994c6b9..907ed8c30 100644
--- a/docs/client-setup.md
+++ b/docs/client-setup.md
@@ -145,7 +145,7 @@ The usual _OpenSSH_ default seems to be 16, but users can ask for more (or less)
Various discussions on the net seem to indicate that 64 is the value at which many computers start to slow down noticeably, so
our default limit seems quite suitable (and beyond) for most cases we are likely to encounter "in the wild".
-### `UserInteraction`
+### <a id="user-interaction"></a>`UserInteraction`
This interface is required for full support of `keyboard-interactive` authentication protocol as described in [RFC-4252 section 9](https://tools.ietf.org/html/rfc4252#section-9).
The client can handle a simple password request from the server, but if more complex challenge-response interaction is required, then this interface must be
@@ -233,6 +233,53 @@ client.start();
client.stop();
```
+### <a id="proxies"></a>Connecting through a client-side SOCKS5 or HTTP CONNECT proxy
+
+If the client has to go through a proxy (typically to allow outgoing traffic through a firewall) to reach the server,
+`client.connect(...)` relies by default on the standard Java `java.net.ProxySelector` using the system default selector
+`ProxySelector.getDefault()`. If the proxy requires authentication credentials, by default the standard `java.net.Authenticator`
+is used to ask the user if no up-front credentials for the proxy are known.
+
+With `ProxySelector.getDefault()`, the default Java [proxy settings](https://docs.oracle.com/javase/8/docs/technotes/guides/net/proxies.html)
+will be respected. Note that the default proxy selector relies on Java system properties being set (for instance, via
+the `-D` option when the Java application is started). It can be made to pick up the OS default settings using
+`-Djava.net.useSystemProxies=true`.
+
+Apache MINA sshd supports
+* HTTP proxies with anonymous, password, or Kerberos5 (SPNEGO) authentication
+* SOCKS proxies using the SOCKS5 protocol with anonymous, password, or Kerberos5 (GSS-API) authentication
+
+Both the way proxies are selected and the way the user is asked for proxy authentication credentials is configurable.
+
+The `SshClient` can be configured with a custom `ProxyDataFactory` to determine which proxy should be used for connecting
+to which remote server address. This `ProxyData` factory can also supply a-priori known proxy authentication credentials
+(user name and password); if set, those will be used and the user won't be asked for them. The `ProxyDataFactory` can be
+set via `SshClient.setProxyDataFactory()`. This gives user code a way to provide a more flexible proxy selection mechanism
+than the built-in default `ProxySelector`.
+
+The UI interaction with the user to ask for proxy authentication credentials can also be customized via the `UserInteraction`
+interface (see also [above](#user-interaction)). Override method `UserInteraction.getProxyCredentials()` to implement custom
+behavior.
+
+Note that neither SOCKS5 nor HTTP CONNECT have any mechanism to ask repeatedly for authentication credentials. SOCKS
+is even specified to disconnect if the credentials are not correct on the first attempt. HTTP proxies will typically
+close the HTTP connection if authentication is required but the credentials are wrong or missing. (In other words: to
+successfully tunnel through an HTTP proxy that requires authentication, you need to supply correct credentials up front.
+With a SOCKS proxy, the user is asked if there are no up-front known credentials.)
+
+Once the authenticated connection to the proxy is established, the client will then ask the proxy to tunnel to the target
+server. If the proxy grants the request, the SSH connection to the target server will start inside the proxy tunnel.
+
+> Note that a SOCKS or HTTP CONNECT connection to the proxy is not encrypted. This is normally fine, as the proxy will be
+> on the boundary of the same firewalled network the SSH client is in, too. Apache MINA sshd has no built-in support for
+> using TLS for connecting the proxy. Doing so would also result in double encryption on the leg between the SSH client and
+> the proxy: first TLS encryption, and then inside that SSH encryption.
+>
+> If you need to connect to a proxy over TLS, you'll have to implement it yourself. We suggest to use the `sshd-mina` or
+> `sshd-netty` I/O transports as a starting point and change them to include a TLS filter in their low-level filter chain
+> (called "pipeline" in Netty). The `IoConnector.connect()` method could examine the `AttributeRepository context` to figure
+> out whether a TLS/SSL filter should be added: if `context.getAttribute(AbstractClientSession.PROXY_DATA) != null`, a proxy
+> is used.
## Configuring the protocol exchange phase
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/ClientBuilder.java b/sshd-core/src/main/java/org/apache/sshd/client/ClientBuilder.java
index b6a4353c4..7876431ee 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/ClientBuilder.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/ClientBuilder.java
@@ -32,6 +32,8 @@ import org.apache.sshd.client.kex.DHGClient;
import org.apache.sshd.client.kex.DHGEXClient;
import org.apache.sshd.client.keyverifier.AcceptAllServerKeyVerifier;
import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
+import org.apache.sshd.client.proxy.DefaultProxyDataFactory;
+import org.apache.sshd.client.proxy.ProxyDataFactory;
import org.apache.sshd.common.BaseBuilder;
import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.channel.ChannelFactory;
@@ -80,6 +82,7 @@ public class ClientBuilder extends BaseBuilder<SshClient, ClientBuilder> {
public static final FilePasswordProvider DEFAULT_FILE_PASSWORD_PROVIDER = FilePasswordProvider.EMPTY;
public static final KexExtensionHandler DEFAULT_KEX_EXTENSION_HANDLER = DefaultClientKexExtensionHandler.INSTANCE;
+ protected ProxyDataFactory proxyDataFactory;
protected ServerKeyVerifier serverKeyVerifier;
protected HostConfigEntryResolver hostConfigEntryResolver;
protected ClientIdentityLoader clientIdentityLoader;
@@ -94,6 +97,11 @@ public class ClientBuilder extends BaseBuilder<SshClient, ClientBuilder> {
return me();
}
+ public ClientBuilder proxyDataFactory(ProxyDataFactory proxyDataFactory) {
+ this.proxyDataFactory = proxyDataFactory;
+ return me();
+ }
+
public ClientBuilder hostConfigEntryResolver(HostConfigEntryResolver resolver) {
this.hostConfigEntryResolver = resolver;
return me();
@@ -137,6 +145,10 @@ public class ClientBuilder extends BaseBuilder<SshClient, ClientBuilder> {
globalRequestHandlers = DEFAULT_GLOBAL_REQUEST_HANDLERS;
}
+ if (proxyDataFactory == null) {
+ proxyDataFactory = new DefaultProxyDataFactory();
+ }
+
if (serverKeyVerifier == null) {
serverKeyVerifier = DEFAULT_SERVER_KEY_VERIFIER;
}
@@ -163,6 +175,7 @@ public class ClientBuilder extends BaseBuilder<SshClient, ClientBuilder> {
@Override
public SshClient build(boolean isFillWithDefaultValues) {
SshClient client = super.build(isFillWithDefaultValues);
+ client.setProxyDataFactory(proxyDataFactory);
client.setServerKeyVerifier(serverKeyVerifier);
client.setHostConfigEntryResolver(hostConfigEntryResolver);
client.setClientIdentityLoader(clientIdentityLoader);
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java b/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
index 22091c646..89291a953 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/SshClient.java
@@ -67,6 +67,8 @@ import org.apache.sshd.client.future.AuthFuture;
import org.apache.sshd.client.future.ConnectFuture;
import org.apache.sshd.client.future.DefaultConnectFuture;
import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.client.proxy.ProxyDataFactory;
import org.apache.sshd.client.session.AbstractClientSession;
import org.apache.sshd.client.session.ClientConnectionServiceFactory;
import org.apache.sshd.client.session.ClientSession;
@@ -187,6 +189,7 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
protected SessionFactory sessionFactory;
protected List<UserAuthFactory> userAuthFactories;
+ private ProxyDataFactory proxyDataFactory;
private ServerKeyVerifier serverKeyVerifier;
private HostConfigEntryResolver hostConfigEntryResolver;
private ClientIdentityLoader clientIdentityLoader;
@@ -214,6 +217,14 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
this.sessionFactory = sessionFactory;
}
+ public ProxyDataFactory getProxyDataFactory() {
+ return proxyDataFactory;
+ }
+
+ public void setProxyDataFactory(ProxyDataFactory proxyDataFactory) {
+ this.proxyDataFactory = proxyDataFactory;
+ }
+
@Override
public ServerKeyVerifier getServerKeyVerifier() {
return serverKeyVerifier;
@@ -600,7 +611,7 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
ExplicitPortForwardingTracker tracker = proxySession
.createLocalPortForwardingTracker(SshdSocketAddress.LOCALHOST_ADDRESS, address);
SshdSocketAddress bound = tracker.getBoundAddress();
- ConnectFuture f4 = doConnect(hostConfig.getUsername(), bound.toInetSocketAddress(),
+ ConnectFuture f4 = doConnect(hostConfig.getUsername(), bound.toInetSocketAddress(), null,
context, localAddress, keys, hostConfig);
toCancel.set(f4);
if (connectFuture.isCanceled()) {
@@ -637,22 +648,34 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
});
return connectFuture;
} else {
- return doConnect(hostConfig.getUsername(), new InetSocketAddress(host, port),
+ // This is a direct connection to an SSH server. Check whether we have to use a proxy (not an SSH
+ // proxyJump).
+ ProxyDataFactory factory = getProxyDataFactory();
+ ProxyData proxy = factory == null ? null : factory.get(targetAddress);
+ return doConnect(hostConfig.getUsername(), targetAddress, proxy,
context, localAddress, keys, hostConfig);
}
}
protected ConnectFuture doConnect(
- String username, SocketAddress targetAddress,
+ String username, InetSocketAddress targetAddress, ProxyData proxy,
AttributeRepository context, SocketAddress localAddress,
KeyIdentityProvider identities, HostConfigEntry hostConfig)
throws IOException {
if (connector == null) {
throw new IllegalStateException("SshClient not started. Please call start() method before connecting to a server");
}
-
Map<AttributeRepository.AttributeKey<?>, Object> sessionAttributes = new HashMap<>();
sessionAttributes.put(AbstractClientSession.HOST_CONFIG_ENTRY, hostConfig);
+ InetSocketAddress connectAddress = targetAddress;
+ if (proxy != null) {
+ sessionAttributes.put(AbstractClientSession.PROXY_DATA, proxy);
+ sessionAttributes.put(TARGET_SERVER, new SshdSocketAddress(targetAddress));
+ connectAddress = proxy.getAddress();
+ if (connectAddress.isUnresolved()) {
+ connectAddress = new InetSocketAddress(connectAddress.getHostName(), connectAddress.getPort());
+ }
+ }
AttributeRepository sessionContext = AttributeRepository.ofAttributesMap(sessionAttributes);
if (context != null) {
sessionContext = new ShadowingAttributeRepository(sessionContext, context);
@@ -660,7 +683,7 @@ public class SshClient extends AbstractFactoryManager implements ClientFactoryMa
ConnectFuture connectFuture = new DefaultConnectFuture(username + "@" + targetAddress, null);
SshFutureListener<IoConnectFuture> listener = createConnectCompletionListener(
connectFuture, username, targetAddress, identities, hostConfig);
- IoConnectFuture connectingFuture = connector.connect(targetAddress, sessionContext, localAddress);
+ IoConnectFuture connectingFuture = connector.connect(connectAddress, sessionContext, localAddress);
connectFuture.addListener(c -> {
if (c.isCanceled()) {
connectingFuture.cancel();
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/auth/keyboard/UserInteraction.java b/sshd-core/src/main/java/org/apache/sshd/client/auth/keyboard/UserInteraction.java
index 53304c44d..5e7a30ebc 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/auth/keyboard/UserInteraction.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/auth/keyboard/UserInteraction.java
@@ -18,6 +18,10 @@
*/
package org.apache.sshd.client.auth.keyboard;
+import java.net.Authenticator;
+import java.net.Authenticator.RequestorType;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
import java.security.KeyPair;
import java.util.List;
@@ -149,7 +153,7 @@ public interface UserInteraction {
String getUpdatedPassword(ClientSession session, String prompt, String lang);
/**
- * Invoked during password authentication when no more pre-registered passwords are available
+ * Invoked during password authentication when no more pre-registered passwords are available.
*
* @param session The {@link ClientSession} through which the request was received
* @return The password to use - {@code null} signals no more passwords available
@@ -159,6 +163,20 @@ public interface UserInteraction {
return null;
}
+ /**
+ * Invoked for proxy authentication using username-password authentication if no credentials are known.
+ *
+ * @param session The {@link ClientSession} through which the request was received
+ * @return The {@link PasswordAuthentication}, or {@code null} to cancel the connection
+ */
+ default PasswordAuthentication getProxyCredentials(ClientSession session, InetSocketAddress proxy) {
+ if (isInteractionAllowed(session)) {
+ return Authenticator.requestPasswordAuthentication(proxy.getHostString(), proxy.getAddress(), proxy.getPort(),
+ "ssh", "Password", "Basic", null, RequestorType.PROXY);
+ }
+ return null;
+ }
+
/**
* Invoked during public key authentication when no more pre-registered keys are available
*
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/proxy/DefaultProxyDataFactory.java b/sshd-core/src/main/java/org/apache/sshd/client/proxy/DefaultProxyDataFactory.java
new file mode 100644
index 000000000..47eb2110e
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/proxy/DefaultProxyDataFactory.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.proxy;
+
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.SocketAddress;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+
+/**
+ * A default implementation of a {@link ProxyDataFactory} based on the standard {@link java.net.ProxySelector}. Prefers
+ * SOCKS proxies over HTTP proxies. If the {@link ProxySelector} returns multiple proxies of the same type, the first
+ * one is chosen.
+ */
+public class DefaultProxyDataFactory implements ProxyDataFactory {
+
+ private final ProxySelector selector;
+
+ /**
+ * Creates an instance that uses {@link ProxySelector#getDefault()}.
+ */
+ public DefaultProxyDataFactory() {
+ this(ProxySelector.getDefault());
+ }
+
+ /**
+ * Creates an instance that uses the given {@link ProxySelector}.
+ *
+ * @param selector {@link ProxySelector} to use; if {@code null}, no {@link ProxyData} will ever be returned.
+ */
+ public DefaultProxyDataFactory(ProxySelector selector) {
+ this.selector = selector;
+ }
+
+ @Override
+ public ProxyData get(InetSocketAddress remoteAddress) {
+ if (selector == null) {
+ return null;
+ }
+ try {
+ List<Proxy> proxies = selector.select(new URI("socket://" + remoteAddress.getHostString()));
+ ProxyData data = getData(proxies);
+ if (data == null) {
+ proxies = selector.select(new URI("https", "//" + remoteAddress.getHostString(), null));
+ data = getData(proxies);
+ }
+ return data;
+ } catch (URISyntaxException e) {
+ return null;
+ }
+ }
+
+ private ProxyData getData(List<Proxy> proxies) {
+ if (proxies.isEmpty()) {
+ return null;
+ }
+ Proxy proxy = proxies.get(0);
+ SocketAddress address = proxy.address();
+ if (!(address instanceof InetSocketAddress)) {
+ return null;
+ }
+ return new ProxyData(proxy);
+ }
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/proxy/ProxyData.java b/sshd-core/src/main/java/org/apache/sshd/client/proxy/ProxyData.java
new file mode 100644
index 000000000..35753e7ab
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/proxy/ProxyData.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.proxy;
+
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.util.Arrays;
+
+/**
+ * An object encapsulating the data needed to connect through a proxy server.
+ */
+public class ProxyData {
+
+ private final Proxy proxy;
+
+ private final String proxyUser;
+
+ private final char[] proxyPassword;
+
+ /**
+ * Creates a new {@link ProxyData} instance without user name or password.
+ *
+ * @param proxy to connect to; must not be {@link java.net.Proxy.Type#DIRECT} and must have an
+ * {@link InetSocketAddress}.
+ */
+ public ProxyData(Proxy proxy) {
+ this(proxy, null, null);
+ }
+
+ /**
+ * Creates a new {@link ProxyData} instance.
+ *
+ * @param proxy to connect to; must not be {@link java.net.Proxy.Type#DIRECT} and must have an
+ * {@link InetSocketAddress}.
+ * @param proxyUser to use for log-in to the proxy, may be {@code null}
+ * @param proxyPassword to use for log-in to the proxy, may be {@code null}
+ */
+ public ProxyData(Proxy proxy, String proxyUser, char[] proxyPassword) {
+ if (!(proxy.address() instanceof InetSocketAddress)) {
+ throw new IllegalArgumentException("Proxy does not have an InetSocketAddress");
+ }
+ this.proxy = proxy;
+ this.proxyUser = proxyUser;
+ this.proxyPassword = proxyPassword == null ? null : proxyPassword.clone();
+ }
+
+ /**
+ * Obtains the {@link InetSocketAddress} to connect to.
+ *
+ * @return the {@link InetSocketAddress}
+ */
+ public InetSocketAddress getAddress() {
+ return (InetSocketAddress) proxy.address();
+ }
+
+ /**
+ * Obtains the {@link Proxy} to connect to.
+ *
+ * @return the {@link Proxy}, never {@code null}
+ */
+ public Proxy.Type getType() {
+ return proxy.type();
+ }
+
+ /**
+ * Obtains the user to log in at the proxy with.
+ *
+ * @return the user name, or {@code null} if none
+ */
+ public String getUser() {
+ return proxyUser;
+ }
+
+ /**
+ * Obtains a copy of the internally stored password.
+ *
+ * @return the password or {@code null} if none
+ */
+ public char[] getPassword() {
+ return proxyPassword == null ? null : proxyPassword.clone();
+ }
+
+ /**
+ * Clears the stored password, if any.
+ */
+ public void clearPassword() {
+ if (proxyPassword != null) {
+ Arrays.fill(proxyPassword, '\000');
+ }
+ }
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/proxy/ProxyDataFactory.java b/sshd-core/src/main/java/org/apache/sshd/client/proxy/ProxyDataFactory.java
new file mode 100644
index 000000000..4727b283d
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/proxy/ProxyDataFactory.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.proxy;
+
+import java.net.InetSocketAddress;
+
+/**
+ * A factory for obtaining {@link ProxyData} to connect through some proxy.
+ */
+public interface ProxyDataFactory {
+
+ /**
+ * Get the {@link ProxyData} to connect to a proxy. It should return a <em>new</em> {@link ProxyData} instance every
+ * time. The caller is responsible for clearing the password, if any, once it is no longer needed.
+ *
+ * @param remoteAddress to connect to
+ * @return the {@link ProxyData} or {@code null} if a direct connection is to be made
+ */
+ ProxyData get(InetSocketAddress remoteAddress);
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/AbstractClientSession.java b/sshd-core/src/main/java/org/apache/sshd/client/session/AbstractClientSession.java
index a5471760e..9ad53d068 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/AbstractClientSession.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/AbstractClientSession.java
@@ -45,6 +45,8 @@ import org.apache.sshd.client.channel.ChannelSubsystem;
import org.apache.sshd.client.channel.ClientChannel;
import org.apache.sshd.client.config.hosts.HostConfigEntry;
import org.apache.sshd.client.keyverifier.ServerKeyVerifier;
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.client.session.filter.ClientProxyFilter;
import org.apache.sshd.common.AttributeRepository;
import org.apache.sshd.common.FactoryManager;
import org.apache.sshd.common.NamedResource;
@@ -81,6 +83,8 @@ public abstract class AbstractClientSession extends AbstractSession implements C
public static final AttributeKey<HostConfigEntry> HOST_CONFIG_ENTRY = new AttributeKey<>();
+ public static final AttributeKey<ProxyData> PROXY_DATA = new AttributeKey<>();
+
protected final boolean sendImmediateClientIdentification;
protected final boolean sendImmediateKexInit;
@@ -113,6 +117,20 @@ public abstract class AbstractClientSession extends AbstractSession implements C
hostConfig = connectionContext.getAttribute(HOST_CONFIG_ENTRY);
}
+ @Override
+ protected void setupFilterChain() {
+ super.setupFilterChain();
+ ProxyData proxy = connectionContext.getAttribute(PROXY_DATA);
+ SshdSocketAddress targetAddress = connectionContext.getAttribute(ClientSessionCreator.TARGET_SERVER);
+ if (proxy != null) {
+ if (targetAddress == null) {
+ throw new IllegalStateException("Have proxy but no target address");
+ }
+ getFilterChain().addFirst(new ClientProxyFilter(this, proxy, targetAddress.toInetSocketAddress()));
+ setAttribute(ClientSessionCreator.TARGET_SERVER, targetAddress);
+ }
+ }
+
@Override
public HostConfigEntry getHostConfigEntry() {
return hostConfig;
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/filter/ClientProxyFilter.java b/sshd-core/src/main/java/org/apache/sshd/client/session/filter/ClientProxyFilter.java
new file mode 100644
index 000000000..599db2711
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/filter/ClientProxyFilter.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.filter;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.net.Proxy;
+import java.util.Objects;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.sshd.client.auth.keyboard.UserInteraction;
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.client.session.AbstractClientSession;
+import org.apache.sshd.client.session.proxy.AbstractProxyConnector;
+import org.apache.sshd.client.session.proxy.HttpProxyConnector;
+import org.apache.sshd.client.session.proxy.Socks5ProxyConnector;
+import org.apache.sshd.common.filter.InputHandler;
+import org.apache.sshd.common.filter.IoFilter;
+import org.apache.sshd.common.filter.OutputHandler;
+import org.apache.sshd.common.future.CloseFuture;
+import org.apache.sshd.common.future.SshFutureListener;
+import org.apache.sshd.common.io.DefaultIoWriteFuture;
+import org.apache.sshd.common.io.IoWriteFuture;
+import org.apache.sshd.common.util.Readable;
+import org.apache.sshd.common.util.buffer.Buffer;
+
+/**
+ * A filter implementing the client-side proxy protocol for tunneling through a SOCKS or HTTP CONNECT proxy. Supports
+ * SOCKS 5 with anonymous access or password or Kerberos 5 authentication, or HTTP CONNECT with anonymous, basic, or
+ * SPNEGO authentication.
+ */
+public class ClientProxyFilter extends IoFilter {
+
+ private final AbstractClientSession session;
+
+ private final AbstractProxyConnector connector;
+
+ private final AtomicReference<InputHandler> input = new AtomicReference<>();
+
+ private final AtomicReference<OutputHandler> output = new AtomicReference<>();
+
+ // We need to be able to queue one, at most two messages: the SSH protocol version message, and the initial
+ // KEX-INIT.
+ private final Queue<Runnable> queue = new ConcurrentLinkedQueue<>();
+
+ private final SshFutureListener<CloseFuture> closer;
+
+ public ClientProxyFilter(AbstractClientSession session, ProxyData proxy, InetSocketAddress targetAddress) {
+ this.session = Objects.requireNonNull(session);
+ connector = proxy.getType() == Proxy.Type.SOCKS
+ ? new Socks5ProxyConnector(proxy, targetAddress, this::write, this::proxyAuth)
+ : new HttpProxyConnector(proxy, targetAddress, this::write, this::proxyAuth);
+ closer = f -> connector.close();
+ session.getIoSession().addCloseFutureListener(closer);
+ input.set(new ProxyInputHandler());
+ output.set(new ProxyOutputHandler());
+ }
+
+ @Override
+ public InputHandler in() {
+ return input.get();
+ }
+
+ @Override
+ public OutputHandler out() {
+ return output.get();
+ }
+
+ // Callback for the connector
+ private IoWriteFuture write(Buffer message) throws IOException {
+ return owner().send(-1, message);
+ }
+
+ private PasswordAuthentication proxyAuth(InetSocketAddress proxyAddress) {
+ UserInteraction ui = session.getUserInteraction();
+ if (ui == null) {
+ return null;
+ }
+ return ui.getProxyCredentials(session, proxyAddress);
+ }
+
+ private class ProxyInputHandler implements InputHandler {
+
+ ProxyInputHandler() {
+ super();
+ }
+
+ @Override
+ public void received(Readable message) throws Exception {
+ if (input.get() == null || connector.isDone()) {
+ owner().passOn(message);
+ } else {
+ Buffer buffer = connector.received(message);
+ if (connector.isDone()) {
+ session.getIoSession().removeCloseFutureListener(closer);
+ connector.close();
+ if (buffer != null && buffer.available() > 0) {
+ buffer.compact();
+ owner().passOn(buffer);
+ }
+ input.set(null);
+ synchronized (queue) {
+ output.set(null);
+ for (;;) {
+ Runnable send = queue.poll();
+ if (send == null) {
+ break;
+ }
+ send.run();
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private class ProxyOutputHandler implements OutputHandler {
+
+ private AtomicBoolean first = new AtomicBoolean(true);
+
+ ProxyOutputHandler() {
+ super();
+ }
+
+ @Override
+ public IoWriteFuture send(int cmd, Buffer message) throws IOException {
+ if (first.compareAndSet(true, false)) {
+ connector.start();
+ }
+ synchronized (queue) {
+ if (output.get() != null) {
+ DefaultIoWriteFuture result = new DefaultIoWriteFuture(this, null);
+ queue.add(() -> {
+ try {
+ owner().send(cmd, message).addListener(w -> {
+ result.setValue(w.isWritten() ? Boolean.TRUE : w.getException());
+ });
+ } catch (IOException e) {
+ result.setValue(e);
+ }
+ });
+ return result;
+ }
+ }
+ return owner().send(cmd, message);
+ }
+
+ }
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AbstractAuthenticationHandler.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AbstractAuthenticationHandler.java
new file mode 100644
index 000000000..36e068af1
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AbstractAuthenticationHandler.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.net.InetSocketAddress;
+
+/**
+ * Abstract base class for {@link AuthenticationHandler}s encapsulating basic common things.
+ *
+ * @param <P> defining the parameter type for the authentication
+ * @param <T> defining the token type for the authentication
+ */
+public abstract class AbstractAuthenticationHandler<P, T> implements AuthenticationHandler<P, T> {
+
+ /** The {@link InetSocketAddress} of the proxy to connect to. */
+ protected InetSocketAddress proxy;
+
+ /** The last set parameters. */
+ protected P params;
+
+ /** A flag telling whether this authentication is done. */
+ protected boolean done;
+
+ /**
+ * Creates a new {@link AbstractAuthenticationHandler} to authenticate with the given {@code proxy}.
+ *
+ * @param proxy the {@link InetSocketAddress} of the proxy to connect to
+ */
+ protected AbstractAuthenticationHandler(InetSocketAddress proxy) {
+ this.proxy = proxy;
+ }
+
+ @Override
+ public final void setParams(P input) {
+ params = input;
+ }
+
+ @Override
+ public final boolean isDone() {
+ return done;
+ }
+
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AbstractProxyConnector.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AbstractProxyConnector.java
new file mode 100644
index 000000000..21dfc7fa3
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AbstractProxyConnector.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.util.Arrays;
+import java.util.Objects;
+import java.util.function.Function;
+
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.common.io.IoWriteFuture;
+import org.apache.sshd.common.util.Readable;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.common.util.io.functors.IOFunction;
+
+/**
+ * Basic common functionality for tunneling through to a proxy.
+ */
+public abstract class AbstractProxyConnector implements Closeable {
+
+ /** The proxy address. */
+ protected final InetSocketAddress proxyAddress;
+
+ /** The ultimate remote address to connect to. */
+ protected final InetSocketAddress remoteAddress;
+
+ protected String proxyUser;
+
+ protected char[] proxyPassword;
+
+ protected boolean done;
+
+ private final IOFunction<Buffer, IoWriteFuture> send;
+
+ private final Function<InetSocketAddress, PasswordAuthentication> passwordAuth;
+
+ /**
+ * Creates a new {@link AbstractProxyConnector}.
+ *
+ * @param proxy {@link ProxyData} of the proxy we're connected to
+ * @param remoteAddress {@link InetSocketAddress} of the target server to connect to
+ * @param send a function to send data and returning an {@link IoWriteFuture}
+ * @param passwordAuth a function to query the user for proxy credentials, if needed, and returning a
+ * {@link PasswordAuthentication}
+ */
+ protected AbstractProxyConnector(ProxyData proxy, InetSocketAddress remoteAddress,
+ IOFunction<Buffer, IoWriteFuture> send,
+ Function<InetSocketAddress, PasswordAuthentication> passwordAuth) {
+ this.proxyAddress = proxy.getAddress();
+ this.proxyUser = proxy.getUser();
+ char[] pass = proxy.getPassword();
+ this.proxyPassword = pass != null ? pass.clone() : new char[0];
+ proxy.clearPassword();
+ this.remoteAddress = Objects.requireNonNull(remoteAddress);
+ this.send = send;
+ this.passwordAuth = passwordAuth;
+ }
+
+ protected IoWriteFuture write(Buffer message) throws IOException {
+ return send.apply(message);
+ }
+
+ protected PasswordAuthentication passwordAuthentication() {
+ return passwordAuth.apply(proxyAddress);
+ }
+
+ protected void clearPassword() {
+ Arrays.fill(proxyPassword, '\000');
+ proxyPassword = new char[0];
+ }
+
+ public boolean isDone() {
+ return done;
+ }
+
+ @Override
+ public void close() {
+ clearPassword();
+ }
+
+ /**
+ * Processes incoming data, and returns a {@link Buffer} containing any extra data from {@code message} that was not
+ * yet processed.
+ *
+ * @param message the received data
+ * @throws Exception if an error occurs
+ */
+ public abstract Buffer received(Readable message) throws Exception;
+
+ /**
+ * Starts the proxy protocol by sending the initial connection request message to the proxy.
+ *
+ * @throws IOException if the message cannot be sent
+ */
+ public abstract void start() throws IOException;
+
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AuthenticationChallenge.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AuthenticationChallenge.java
new file mode 100644
index 000000000..057acb66b
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AuthenticationChallenge.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+/**
+ * A simple representation of an authentication challenge as sent in a "WWW-Authenticate" or "Proxy-Authenticate"
+ * header. Such challenges start with a mechanism name, followed either by one single token, or by a list of key=value
+ * pairs.
+ *
+ * @see <a href="https://tools.ietf.org/html/rfc7235#section-2.1">RFC 7235, sec. 2.1</a>
+ */
+public class AuthenticationChallenge {
+
+ private final String mechanism;
+
+ private String token;
+
+ private Map<String, String> arguments;
+
+ /**
+ * Create a new {@link AuthenticationChallenge} with the given mechanism.
+ *
+ * @param mechanism for the challenge
+ */
+ public AuthenticationChallenge(String mechanism) {
+ this.mechanism = mechanism;
+ }
+
+ /**
+ * Retrieves the authentication mechanism specified by this challenge, for instance "Basic".
+ *
+ * @return the mechanism name
+ */
+ public String getMechanism() {
+ return mechanism;
+ }
+
+ /**
+ * Retrieves the token of the challenge, if any.
+ *
+ * @return the token, or {@code null} if there is none.
+ */
+ public String getToken() {
+ return token;
+ }
+
+ /**
+ * Retrieves the arguments of the challenge.
+ *
+ * @return a possibly empty map of the key=value arguments of the challenge
+ */
+ public Map<String, String> getArguments() {
+ return arguments == null ? Collections.emptyMap() : arguments;
+ }
+
+ void addArgument(String key, String value) {
+ if (arguments == null) {
+ arguments = new LinkedHashMap<>();
+ }
+ arguments.put(key, value);
+ }
+
+ void setToken(String token) {
+ this.token = token;
+ }
+
+ @Override
+ public String toString() {
+ return "AuthenticationChallenge[" + mechanism + ',' + token + ',' //$NON-NLS-1$
+ + (arguments == null ? "<none>" : arguments.toString()) + ']'; //$NON-NLS-1$
+ }
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AuthenticationHandler.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AuthenticationHandler.java
new file mode 100644
index 000000000..c3331ff7a
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/AuthenticationHandler.java
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.io.Closeable;
+import java.io.IOException;
+
+/**
+ * An {@code AuthenticationHandler} encapsulates a possibly multi-step authentication protocol. Intended usage:
+ *
+ * <pre>
+ * setParams(something);
+ * start();
+ * sendToken(getToken());
+ * while (!isDone()) {
+ * setParams(receiveMessageAndExtractParams());
+ * process();
+ * Object t = getToken();
+ * if (t != null) {
+ * sendToken(t);
+ * }
+ * }
+ * </pre>
+ *
+ * An {@code AuthenticationHandler} may be stateful and therefore is a {@link Closeable}.
+ *
+ * @param <P> defining the parameter type for {@link #setParams(Object)}
+ * @param <T> defining the token type for {@link #getToken()}
+ */
+public interface AuthenticationHandler<P, T> extends Closeable {
+
+ /**
+ * Produces the initial authentication token that can be then retrieved via {@link #getToken()}.
+ *
+ * @throws Exception if an error occurs
+ */
+ void start() throws IOException;
+
+ /**
+ * Produces the next authentication token, if any.
+ *
+ * @throws Exception if an error occurs
+ */
+ void process() throws Exception;
+
+ /**
+ * Sets the parameters for the next token generation via {@link #start()} or {@link #process()}.
+ *
+ * @param input to set, may be {@code null}
+ */
+ void setParams(P input);
+
+ /**
+ * Retrieves the last token generated.
+ *
+ * @return the token, or {@code null} if there is none
+ * @throws Exception if an error occurs
+ */
+ T getToken() throws IOException;
+
+ /**
+ * Tells whether is authentication mechanism is done (successfully or unsuccessfully).
+ *
+ * @return whether this authentication is done
+ */
+ boolean isDone();
+
+ @Override
+ void close();
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/BasicAuthentication.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/BasicAuthentication.java
new file mode 100644
index 000000000..1197e3ad6
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/BasicAuthentication.java
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.io.IOException;
+import java.net.Authenticator;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.nio.ByteBuffer;
+import java.nio.CharBuffer;
+import java.util.Arrays;
+import java.util.concurrent.CancellationException;
+
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+/**
+ * An abstract implementation of a username-password authentication. It can be given an initial known username-password
+ * pair; if so, this will be tried first. Subsequent rounds will then try to obtain a user name and password via the
+ * global {@link Authenticator}.
+ *
+ * @param <P> defining the parameter type for the authentication
+ * @param <T> defining the token type for the authentication
+ */
+public abstract class BasicAuthentication<P, T> extends AbstractAuthenticationHandler<P, T> {
+
+ /** The current user name. */
+ protected String user;
+
+ /** The current password. */
+ protected byte[] password;
+
+ /**
+ * Creates a new {@link BasicAuthentication} to authenticate with the given {@code proxy}.
+ *
+ * @param proxy {@link InetSocketAddress} of the proxy to connect to
+ * @param initialUser initial user name to try; may be {@code null}
+ * @param initialPassword initial password to try, may be {@code null}
+ */
+ protected BasicAuthentication(InetSocketAddress proxy, String initialUser, char[] initialPassword) {
+ super(proxy);
+ this.user = initialUser;
+ this.password = convert(initialPassword);
+ }
+
+ @SuppressWarnings("ByteBufferBackingArray")
+ private byte[] convert(char[] pass) {
+ if (pass == null) {
+ return new byte[0];
+ }
+ ByteBuffer bytes = UTF_8.encode(CharBuffer.wrap(pass));
+ byte[] pwd = new byte[bytes.remaining()];
+ bytes.get(pwd);
+ if (bytes.hasArray()) {
+ Arrays.fill(bytes.array(), (byte) 0);
+ }
+ Arrays.fill(pass, '\000');
+ return pwd;
+ }
+
+ /**
+ * Clears the {@link #password}.
+ */
+ protected void clearPassword() {
+ if (password != null) {
+ Arrays.fill(password, (byte) 0);
+ }
+ password = new byte[0];
+ }
+
+ @Override
+ public final void close() {
+ clearPassword();
+ done = true;
+ }
+
+ @Override
+ public final void start() throws IOException {
+ if ((user != null && !user.isEmpty()) || (password != null && password.length > 0)) {
+ return;
+ }
+ askCredentials();
+ }
+
+ @Override
+ public void process() throws Exception {
+ askCredentials();
+ }
+
+ /**
+ * Asks for credentials via the global {@link Authenticator}.
+ */
+ protected void askCredentials() {
+ clearPassword();
+ PasswordAuthentication auth = getCredentials();
+ if (auth == null) {
+ user = ""; //$NON-NLS-1$
+ throw new CancellationException("Proxy authentication cancelled by user");
+ }
+ user = auth.getUserName();
+ password = convert(auth.getPassword());
+ }
+
+ protected abstract PasswordAuthentication getCredentials();
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/GssApiAuthentication.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/GssApiAuthentication.java
new file mode 100644
index 000000000..dd6676b4a
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/GssApiAuthentication.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+
+import org.ietf.jgss.GSSContext;
+
+/**
+ * An abstract implementation of a GSS-API multi-round authentication.
+ *
+ * @param <P> defining the parameter type for the authentication
+ * @param <T> defining the token type for the authentication
+ */
+public abstract class GssApiAuthentication<P, T> extends AbstractAuthenticationHandler<P, T> {
+
+ /** The last token generated. */
+ protected byte[] token;
+
+ private GSSContext context;
+
+ /**
+ * Creates a new {@link GssApiAuthentication} to authenticate with the given {@code proxy}.
+ *
+ * @param proxy the {@link InetSocketAddress} of the proxy to connect to
+ */
+ protected GssApiAuthentication(InetSocketAddress proxy) {
+ super(proxy);
+ }
+
+ @Override
+ public void close() {
+ GssApiMechanisms.closeContextSilently(context);
+ context = null;
+ done = true;
+ }
+
+ @Override
+ public final void start() throws IOException {
+ try {
+ context = createContext();
+ context.requestMutualAuth(true);
+ context.requestConf(false);
+ context.requestInteg(false);
+ byte[] empty = new byte[0];
+ token = context.initSecContext(empty, 0, 0);
+ } catch (Exception e) {
+ close();
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public final void process() throws Exception {
+ if (context == null) {
+ throw new IOException("Cannot authenticate using GSS-API at " + proxy);
+ }
+ try {
+ byte[] received = extractToken(params);
+ token = context.initSecContext(received, 0, received.length);
+ checkDone();
+ } catch (Exception e) {
+ close();
+ throw e;
+ }
+ }
+
+ private void checkDone() throws Exception {
+ done = context.isEstablished();
+ if (done) {
+ context.dispose();
+ context = null;
+ }
+ }
+
+ /**
+ * Creates the {@link GSSContext} to use.
+ *
+ * @return a fresh {@link GSSContext} to use
+ * @throws Exception if the context cannot be created
+ */
+ protected abstract GSSContext createContext() throws Exception;
+
+ /**
+ * Extracts the token from the last set parameters.
+ *
+ * @param input to extract the token from
+ * @return the extracted token, or {@code null} if none
+ * @throws Exception if an error occurs
+ */
+ protected abstract byte[] extractToken(P input) throws Exception;
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/GssApiMechanisms.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/GssApiMechanisms.java
new file mode 100644
index 000000000..9d966d245
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/GssApiMechanisms.java
@@ -0,0 +1,192 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.UnknownHostException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.ietf.jgss.GSSContext;
+import org.ietf.jgss.GSSException;
+import org.ietf.jgss.GSSManager;
+import org.ietf.jgss.GSSName;
+import org.ietf.jgss.Oid;
+
+/**
+ * Global repository of GSS-API mechanisms that we can use.
+ */
+public final class GssApiMechanisms {
+
+ /** Prefix to use with {@link GSSName#NT_HOSTBASED_SERVICE}. */
+ public static final String GSSAPI_HOST_PREFIX = "host@"; //$NON-NLS-1$
+
+ /** The {@link Oid} of Kerberos 5. */
+ public static final Oid KERBEROS_5 = createOid("1.2.840.113554.1.2.2"); //$NON-NLS-1$
+
+ /** SGNEGO is not to be used with ssh. */
+ public static final Oid SPNEGO = createOid("1.3.6.1.5.5.2"); //$NON-NLS-1$
+
+ /** Protects {@link #supportedMechanisms}. */
+ private static final Object LOCK = new Object();
+
+ /**
+ * The {@link AtomicBoolean} is set to {@code true} when the mechanism could be initialized successfully at least
+ * once.
+ */
+ private static Map<Oid, Boolean> supportedMechanisms;
+
+ private GssApiMechanisms() {
+ // No instantiation
+ }
+
+ /**
+ * Retrieves an immutable collection of the supported mechanisms.
+ *
+ * @return the supported mechanisms
+ */
+ public static Collection<Oid> getSupportedMechanisms() {
+ synchronized (LOCK) {
+ if (supportedMechanisms == null) {
+ GSSManager manager = GSSManager.getInstance();
+ Oid[] mechs = manager.getMechs();
+ Map<Oid, Boolean> mechanisms = new LinkedHashMap<>();
+ if (mechs != null) {
+ for (Oid oid : mechs) {
+ mechanisms.put(oid, Boolean.FALSE);
+ }
+ }
+ supportedMechanisms = mechanisms;
+ }
+ return Collections.unmodifiableSet(supportedMechanisms.keySet());
+ }
+ }
+
+ /**
+ * Report that this mechanism was used successfully.
+ *
+ * @param mechanism that worked
+ */
+ public static void worked(Oid mechanism) {
+ synchronized (LOCK) {
+ supportedMechanisms.put(mechanism, Boolean.TRUE);
+ }
+ }
+
+ /**
+ * Mark the mechanisms as failed.
+ *
+ * @param mechanism to mark
+ */
+ public static void failed(Oid mechanism) {
+ synchronized (LOCK) {
+ Boolean worked = supportedMechanisms.get(mechanism);
+ if (worked != null && !worked.booleanValue()) {
+ // If it never worked, remove it
+ supportedMechanisms.remove(mechanism);
+ }
+ }
+ }
+
+ /**
+ * Resolves an {@link InetSocketAddress}.
+ *
+ * @param remote to resolve
+ * @return the resolved {@link InetAddress}, or {@code null} if unresolved.
+ */
+ public static InetAddress resolve(InetSocketAddress remote) {
+ InetAddress address = remote.getAddress();
+ if (address == null) {
+ try {
+ address = InetAddress.getByName(remote.getHostString());
+ } catch (UnknownHostException e) {
+ return null;
+ }
+ }
+ return address;
+ }
+
+ /**
+ * Determines a canonical host name for use use with GSS-API.
+ *
+ * @param remote to get the host name from
+ * @return the canonical host name, if it can be determined, otherwise the
+ * {@link InetSocketAddress#getHostString() unprocessed host name}.
+ */
+ public static String getCanonicalName(InetSocketAddress remote) {
+ InetAddress address = resolve(remote);
+ if (address == null) {
+ return remote.getHostString();
+ }
+ return address.getCanonicalHostName();
+ }
+
+ /**
+ * Creates a {@link GSSContext} for the given mechanism to authenticate with the host given by {@code fqdn}.
+ *
+ * @param mechanism {@link Oid} of the mechanism to use
+ * @param fqdn fully qualified domain name of the host to authenticate with
+ * @return the context, if the mechanism is available and the context could be created, or {@code null}
+ * otherwise
+ */
+ public static GSSContext createContext(Oid mechanism, String fqdn) {
+ GSSContext context = null;
+ try {
+ GSSManager manager = GSSManager.getInstance();
+ context = manager.createContext(
+ manager.createName(GssApiMechanisms.GSSAPI_HOST_PREFIX + fqdn, GSSName.NT_HOSTBASED_SERVICE), mechanism,
+ null, GSSContext.DEFAULT_LIFETIME);
+ } catch (GSSException e) {
+ closeContextSilently(context);
+ failed(mechanism);
+ return null;
+ }
+ worked(mechanism);
+ return context;
+ }
+
+ /**
+ * Closes (disposes of) a {@link GSSContext} ignoring any {@link GSSException}s.
+ *
+ * @param context to dispose
+ */
+ public static void closeContextSilently(GSSContext context) {
+ if (context != null) {
+ try {
+ context.dispose();
+ } catch (GSSException e) {
+ // Ignore
+ }
+ }
+ }
+
+ private static Oid createOid(String rep) {
+ try {
+ return new Oid(rep);
+ } catch (GSSException e) {
+ // Does not occur
+ return null;
+ }
+ }
+
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/HttpParser.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/HttpParser.java
new file mode 100644
index 000000000..f4195a6d7
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/HttpParser.java
@@ -0,0 +1,336 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+/**
+ * A basic parser for HTTP response headers. Handles status lines and authentication headers (WWW-Authenticate,
+ * Proxy-Authenticate).
+ *
+ * @see <a href="https://tools.ietf.org/html/rfc7230">RFC 7230</a>
+ * @see <a href="https://tools.ietf.org/html/rfc7235">RFC 7235</a>
+ */
+public final class HttpParser {
+
+ /**
+ * An exception indicating some problem parsing HTPP headers.
+ */
+ public static class ParseException extends Exception {
+
+ private static final long serialVersionUID = -1634090143702048640L;
+
+ /**
+ * Creates a new {@link ParseException} without cause.
+ */
+ public ParseException() {
+ super();
+ }
+
+ /**
+ * Creates a new {@link ParseException} with the given {@code cause}.
+ *
+ * @param cause {@link Throwable} that caused this exception, or {@code null} if none
+ */
+ public ParseException(Throwable cause) {
+ super(cause);
+ }
+ }
+
+ private HttpParser() {
+ // No instantiation
+ }
+
+ /**
+ * Parse a HTTP response status line.
+ *
+ * @param line to parse
+ * @return the {@link StatusLine}
+ * @throws ParseException if the line cannot be parsed or has the wrong HTTP version
+ */
+ public static StatusLine parseStatusLine(String line) throws ParseException {
+ // Format is HTTP/<version> Code Reason
+ int firstBlank = line.indexOf(' ');
+ if (firstBlank < 0) {
+ throw new ParseException();
+ }
+ int secondBlank = line.indexOf(' ', firstBlank + 1);
+ if (secondBlank < 0) {
+ // Accept the line even if the (according to RFC 2616 mandatory)
+ // reason is missing.
+ secondBlank = line.length();
+ }
+ int resultCode;
+ try {
+ resultCode = Integer.parseUnsignedInt(line.substring(firstBlank + 1, secondBlank));
+ } catch (NumberFormatException e) {
+ throw new ParseException(e);
+ }
+ // Again, accept even if the reason is missing
+ String reason = ""; //$NON-NLS-1$
+ if (secondBlank < line.length()) {
+ reason = line.substring(secondBlank + 1);
+ }
+ return new StatusLine(line.substring(0, firstBlank), resultCode, reason);
+ }
+
+ /**
+ * Extract the authentication headers from the header lines. It is assumed that the first element in {@code reply}
+ * is the raw status line as received from the server. It is skipped. Line processing stops on the first empty line
+ * thereafter.
+ *
+ * @param reply The complete (header) lines of the HTTP response
+ * @param authenticationHeader to look for (including the terminating ':'!)
+ * @return a list of {@link AuthenticationChallenge}s found.
+ */
+ public static List<AuthenticationChallenge> getAuthenticationHeaders(List<String> reply, String authenticationHeader) {
+ List<AuthenticationChallenge> challenges = new ArrayList<>();
+ Iterator<String> lines = reply.iterator();
+ // We know we have at least one line. Skip the response line.
+ lines.next();
+ StringBuilder value = null;
+ while (lines.hasNext()) {
+ String line = lines.next();
+ if (line.isEmpty()) {
+ break;
+ }
+ if (Character.isWhitespace(line.charAt(0))) {
+ // Continuation line.
+ if (value == null) {
+ // Skip if we have no current value
+ continue;
+ }
+ // Skip leading whitespace
+ int i = skipWhiteSpace(line, 1);
+ value.append(' ').append(line, i, line.length());
+ continue;
+ }
+ if (value != null) {
+ parseChallenges(challenges, value.toString());
+ value = null;
+ }
+ int firstColon = line.indexOf(':');
+ if (firstColon > 0 && authenticationHeader.equalsIgnoreCase(line.substring(0, firstColon + 1))) {
+ value = new StringBuilder(line.substring(firstColon + 1));
+ }
+ }
+ if (value != null) {
+ parseChallenges(challenges, value.toString());
+ }
+ return challenges;
+ }
+
+ private static void parseChallenges(List<AuthenticationChallenge> challenges, String header) {
+ // Comma-separated list of challenges, each itself a scheme name
+ // followed optionally by either: a comma-separated list of key=value
+ // pairs, where the value may be a quoted string with backslash escapes,
+ // or a single token value, which itself may end in zero or more '='
+ // characters. Ugh.
+ int length = header.length();
+ for (int i = 0; i < length;) {
+ int start = skipWhiteSpace(header, i);
+ int end = scanToken(header, start);
+ if (end <= start) {
+ break;
+ }
+ AuthenticationChallenge challenge = new AuthenticationChallenge(header.substring(start, end));
+ challenges.add(challenge);
+ i = parseChallenge(challenge, header, end);
+ }
+ }
+
+ private static int parseChallenge(AuthenticationChallenge challenge, String header, int from) {
+ int length = header.length();
+ boolean first = true;
+ for (int start = from; start <= length; first = false) {
+ // Now we have either a single token, which may end in zero or more
+ // equal signs, or a comma-separated list of key=value pairs (with
+ // optional legacy whitespace around the equals sign), where the
+ // value can be either a token or a quoted string.
+ start = skipWhiteSpace(header, start);
+ int end = scanToken(header, start);
+ if (end == start) {
+ // Nothing found. Either at end or on a comma.
+ if (start < header.length() && header.charAt(start) == ',') {
+ return start + 1;
+ }
+ return start;
+ }
+ int next = skipWhiteSpace(header, end);
+ // Comma, or equals sign, or end of string
+ if (next >= length || header.charAt(next) != '=') {
+ if (first) {
+ // It must be a token
+ challenge.setToken(header.substring(start, end));
+ if (next < length && header.charAt(next) == ',') {
+ next++;
+ }
+ return next;
+ }
+ // This token must be the name of the next authentication
+ // scheme.
+ return start;
+ }
+ int nextStart = skipWhiteSpace(header, next + 1);
+ if (nextStart >= length) {
+ if (next == end) {
+ // '=' immediately after the key, no value: key must be the
+ // token, and the equals sign is part of the token
+ challenge.setToken(header.substring(start, end + 1));
+ } else {
+ // Key without value...
+ challenge.addArgument(header.substring(start, end), null);
+ }
+ return nextStart;
+ }
+ if (nextStart == end + 1 && header.charAt(nextStart) == '=') {
+ // More than one equals sign: must be the single token.
+ end = nextStart + 1;
+ while (end < length && header.charAt(end) == '=') {
+ end++;
+ }
+ challenge.setToken(header.substring(start, end));
+ end = skipWhiteSpace(header, end);
+ if (end < length && header.charAt(end) == ',') {
+ end++;
+ }
+ return end;
+ }
+ if (header.charAt(nextStart) == ',') {
+ if (next == end) {
+ // '=' immediately after the key, no value: key must be the
+ // token, and the equals sign is part of the token
+ challenge.setToken(header.substring(start, end + 1));
+ return nextStart + 1;
+ }
+ // Key without value...
+ challenge.addArgument(header.substring(start, end), null);
+ start = nextStart + 1;
+ } else {
+ if (header.charAt(nextStart) == '"') {
+ int[] nextEnd = { nextStart + 1 };
+ String value = scanQuotedString(header, nextStart + 1, nextEnd);
+ challenge.addArgument(header.substring(start, end), value);
+ start = nextEnd[0];
+ } else {
+ int nextEnd = scanToken(header, nextStart);
+ challenge.addArgument(header.substring(start, end), header.substring(nextStart, nextEnd));
+ start = nextEnd;
+ }
+ start = skipWhiteSpace(header, start);
+ if (start < length && header.charAt(start) == ',') {
+ start++;
+ }
+ }
+ }
+ return length;
+ }
+
+ private static int skipWhiteSpace(String header, int i) {
+ int length = header.length();
+ while (i < length && Character.isWhitespace(header.charAt(i))) {
+ i++;
+ }
+ return i;
+ }
+
+ private static String scanQuotedString(String header, int from, int[] to) {
+ StringBuilder result = new StringBuilder();
+ int length = header.length();
+ boolean quoted = false;
+ int i = from;
+ while (i < length) {
+ char c = header.charAt(i++);
+ if (quoted) {
+ result.append(c);
+ quoted = false;
+ } else if (c == '\\') {
+ quoted = true;
+ } else if (c == '"') {
+ break;
+ } else {
+ result.append(c);
+ }
+ }
+ to[0] = i;
+ return result.toString();
+ }
+
+ /**
+ * Scan a RFC 7230 token as it appears in HTTP headers.
+ *
+ * @param header to scan in
+ * @param from index in {@code header} to start scanning at
+ * @return the index after the token, that is, on the first non-token character or
+ * {@code header.length}
+ * @throws IndexOutOfBoundsException if {@code from < 0} or {@code from > header.length()}
+ *
+ * @see <a href="https://tools.ietf.org/html/rfc7230#appendix-B">RFC 7230, Appendix B:
+ * Collected Grammar; "token" production</a>
+ */
+ private static int scanToken(String header, int from) {
+ int length = header.length();
+ int i = from;
+ if (i < 0 || i > length) {
+ throw new IndexOutOfBoundsException();
+ }
+ while (i < length) {
+ char c = header.charAt(i);
+ switch (c) {
+ case '!':
+ case '#':
+ case '$':
+ case '%':
+ case '&':
+ case '\'':
+ case '*':
+ case '+':
+ case '-':
+ case '.':
+ case '^':
+ case '_':
+ case '`':
+ case '|':
+ case '~':
+ case '0':
+ case '1':
+ case '2':
+ case '3':
+ case '4':
+ case '5':
+ case '6':
+ case '7':
+ case '8':
+ case '9':
+ i++;
+ break;
+ default:
+ if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) {
+ i++;
+ break;
+ }
+ return i;
+ }
+ }
+ return i;
+ }
+
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/HttpProxyConnector.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/HttpProxyConnector.java
new file mode 100644
index 000000000..75d981fac
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/HttpProxyConnector.java
@@ -0,0 +1,351 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Base64;
+import java.util.Iterator;
+import java.util.List;
+import java.util.function.Function;
+
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.common.io.IoWriteFuture;
+import org.apache.sshd.common.util.Readable;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
+import org.apache.sshd.common.util.io.functors.IOFunction;
+import org.ietf.jgss.GSSContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.nio.charset.StandardCharsets.US_ASCII;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+/**
+ * Simple HTTP proxy connector supporting Basic and SPNEGO Authentication.
+ */
+@SuppressWarnings("checkstyle:MethodCount")
+public class HttpProxyConnector extends AbstractProxyConnector {
+
+ private static final Logger LOG = LoggerFactory.getLogger(HttpProxyConnector.class);
+
+ private static final String HTTP_V11 = "HTTP/1.1";
+
+ private static final String HTTP_HEADER_PROXY_AUTHENTICATE = "Proxy-Authenticate:";
+
+ private static final String HTTP_HEADER_PROXY_AUTHORIZATION = "Proxy-Authorization:";
+
+ private HttpAuthenticationHandler basic;
+
+ private HttpAuthenticationHandler negotiate;
+
+ private List<HttpAuthenticationHandler> availableAuthentications;
+
+ private Iterator<HttpAuthenticationHandler> clientAuthentications;
+
+ private HttpAuthenticationHandler authenticator;
+
+ private boolean ongoing;
+
+ /**
+ * Creates a new {@link HttpProxyConnector}. The connector supports anonymous proxy connections as well as Basic and
+ * Negotiate (SPNEGO) authentication.
+ *
+ * @param proxy {@link ProxyData} of the proxy we're connected to
+ * @param remoteAddress {@link InetSocketAddress} of the target server to connect to
+ * @param send a function to send data and returning an {@link IoWriteFuture}
+ * @param passwordAuth a function to query the user for proxy credentials, if needed, and returning a
+ * {@link PasswordAuthentication}
+ */
+ public HttpProxyConnector(ProxyData proxy, InetSocketAddress remoteAddress, IOFunction<Buffer, IoWriteFuture> send,
+ Function<InetSocketAddress, PasswordAuthentication> passwordAuth) {
+ super(proxy, remoteAddress, send, passwordAuth);
+ basic = new HttpBasicAuthentication();
+ negotiate = new NegotiateAuthentication();
+ availableAuthentications = new ArrayList<>(2);
+ availableAuthentications.add(negotiate);
+ availableAuthentications.add(basic);
+ clientAuthentications = availableAuthentications.iterator();
+ }
+
+ @Override
+ public void close() {
+ super.close();
+ HttpAuthenticationHandler current = authenticator;
+ authenticator = null;
+ if (current != null) {
+ current.close();
+ }
+ }
+
+ @Override
+ public void start() throws IOException {
+ StringBuilder msg = connect();
+ if ((proxyUser != null && !proxyUser.isEmpty()) || (proxyPassword != null && proxyPassword.length > 0)) {
+ authenticator = basic;
+ basic.setParams(null);
+ basic.start();
+ msg = authenticate(msg, basic.getToken());
+ clearPassword();
+ proxyUser = null;
+ }
+ ongoing = true;
+ try {
+ send(msg);
+ } catch (IOException e) {
+ ongoing = false;
+ throw e;
+ }
+ }
+
+ private void send(StringBuilder msg) throws IOException {
+ byte[] data = eol(msg).toString().getBytes(US_ASCII);
+ Buffer buffer = new ByteArrayBuffer(data.length, false);
+ buffer.putRawBytes(data);
+ write(buffer);
+ }
+
+ private StringBuilder connect() {
+ StringBuilder msg = new StringBuilder();
+ // Persistent connections are the default in HTTP 1.1 (see RFC 2616), but let's be explicit.
+ return msg.append(MessageFormat.format(
+ "CONNECT {0}:{1} {2}\r\nProxy-Connection: keep-alive\r\nConnection: keep-alive\r\nHost: {0}:{1}\r\n",
+ remoteAddress.getHostString(), Integer.toString(remoteAddress.getPort()), HTTP_V11));
+ }
+
+ private StringBuilder authenticate(StringBuilder msg, String token) {
+ msg.append(HTTP_HEADER_PROXY_AUTHORIZATION).append(' ').append(token);
+ return eol(msg);
+ }
+
+ private StringBuilder eol(StringBuilder msg) {
+ return msg.append('\r').append('\n');
+ }
+
+ @Override
+ public Buffer received(Readable buffer) throws Exception {
+ try {
+ int length = buffer.available();
+ byte[] data = new byte[length];
+ buffer.getRawBytes(data, 0, length);
+ Buffer rest = null;
+ // HTTP responses end with two CRLFs. Find them.
+ String msg = new String(data, US_ASCII);
+ int end = msg.indexOf("\r\n\r\n");
+ if (end < 0) {
+ end = data.length;
+ } else {
+ end += 4;
+ }
+ if (end < data.length) {
+ msg = msg.substring(0, end);
+ data = Arrays.copyOfRange(data, end, data.length);
+ rest = new ByteArrayBuffer(data);
+ }
+ String[] reply = msg.split("\r\n");
+ handleMessage(Arrays.asList(reply));
+ return rest;
+ } catch (Exception e) {
+ if (authenticator != null) {
+ authenticator.close();
+ authenticator = null;
+ }
+ ongoing = false;
+ done = true;
+ throw e;
+ }
+ }
+
+ private void handleMessage(List<String> reply) throws Exception {
+ if (reply.isEmpty() || reply.get(0).isEmpty()) {
+ throw new IOException("Unexpected empty reply from proxy " + proxyAddress);
+ }
+ try {
+ StatusLine status = HttpParser.parseStatusLine(reply.get(0));
+ if (!ongoing) {
+ throw new IOException(MessageFormat.format("Unexpected reply from proxy {0}; {1} status {2}: {3}", proxyAddress,
+ status.getVersion(), Integer.toString(status.getResultCode()), status.getReason()));
+ }
+ switch (status.getResultCode()) {
+ case HttpURLConnection.HTTP_OK:
+ if (authenticator != null) {
+ authenticator.close();
+ }
+ authenticator = null;
+ ongoing = false;
+ done = true;
+ break;
+ case HttpURLConnection.HTTP_PROXY_AUTH:
+ boolean closesConnection = reply.stream().anyMatch("Connection: close"::equals);
+ if (closesConnection) {
+ LOG.warn("{} proxy closed connection; needs up-front pre-emptive proxy authentication",
+ status.getVersion());
+ }
+ List<AuthenticationChallenge> challenges = HttpParser.getAuthenticationHeaders(reply,
+ HTTP_HEADER_PROXY_AUTHENTICATE);
+ authenticator = selectProtocol(challenges, authenticator);
+ if (authenticator == null) {
+ throw new IOException("Cannot authenticate at proxy " + proxyAddress);
+ }
+ String token = authenticator.getToken();
+ if (token == null) {
+ throw new IOException("Cannot authenticate at proxy " + proxyAddress);
+ }
+ send(authenticate(connect(), token));
+ break;
+ default:
+ throw new IOException(MessageFormat.format("HTTP proxy failure at {0}, HTTP status {1}: {2}", proxyAddress,
+ Integer.toString(status.getResultCode()), status.getReason()));
+ }
+ } catch (HttpParser.ParseException e) {
+ throw new IOException(MessageFormat.format("Cannot parse reply from proxy {0}: {1}", proxyAddress, reply.get(0)),
+ e);
+ }
+ }
+
+ private HttpAuthenticationHandler selectProtocol(
+ List<AuthenticationChallenge> challenges,
+ HttpAuthenticationHandler current) throws Exception {
+ if (current != null && !current.isDone()) {
+ AuthenticationChallenge challenge = getByName(challenges, current.getName());
+ if (challenge != null) {
+ current.setParams(challenge);
+ current.process();
+ return current;
+ }
+ }
+ if (current != null) {
+ current.close();
+ }
+ while (clientAuthentications.hasNext()) {
+ HttpAuthenticationHandler next = clientAuthentications.next();
+ if (!next.isDone()) {
+ AuthenticationChallenge challenge = getByName(challenges, next.getName());
+ if (challenge != null) {
+ next.setParams(challenge);
+ next.start();
+ return next;
+ }
+ }
+ }
+ return null;
+ }
+
+ private AuthenticationChallenge getByName(List<AuthenticationChallenge> challenges, String name) {
+ return challenges.stream().filter(c -> c.getMechanism().equalsIgnoreCase(name)).findFirst().orElse(null);
+ }
+
+ private interface HttpAuthenticationHandler extends AuthenticationHandler<AuthenticationChallenge, String> {
+
+ String getName();
+ }
+
+ /**
+ * @see <a href="https://tools.ietf.org/html/rfc7617">RFC 7617</a>
+ */
+ private class HttpBasicAuthentication extends BasicAuthentication<AuthenticationChallenge, String>
+ implements HttpAuthenticationHandler {
+
+ private boolean asked;
+
+ HttpBasicAuthentication() {
+ super(proxyAddress, proxyUser, proxyPassword);
+ }
+
+ @Override
+ public String getName() {
+ return "Basic";
+ }
+
+ @Override
+ protected void askCredentials() {
+ // We ask only once.
+ if (asked) {
+ throw new IllegalStateException("Basic auth: already asked user for password");
+ }
+ asked = true;
+ super.askCredentials();
+ done = true;
+ }
+
+ @Override
+ protected PasswordAuthentication getCredentials() {
+ return passwordAuthentication();
+ }
+
+ @Override
+ public String getToken() throws IOException {
+ if (user.indexOf(':') >= 0) {
+ throw new IOException(MessageFormat.format("Invalid user name ''{0}'' for proxy {1}", user, proxy));
+ }
+ byte[] rawUser = user.getBytes(UTF_8);
+ byte[] toEncode = new byte[rawUser.length + 1 + password.length];
+ System.arraycopy(rawUser, 0, toEncode, 0, rawUser.length);
+ toEncode[rawUser.length] = ':';
+ System.arraycopy(password, 0, toEncode, rawUser.length + 1, password.length);
+ Arrays.fill(password, (byte) 0);
+ String result = Base64.getEncoder().encodeToString(toEncode);
+ Arrays.fill(toEncode, (byte) 0);
+ return getName() + ' ' + result;
+ }
+
+ }
+
+ /**
+ * @see <a href="https://tools.ietf.org/html/rfc4559">RFC 4559</a>
+ */
+ private class NegotiateAuthentication extends GssApiAuthentication<AuthenticationChallenge, String>
+ implements HttpAuthenticationHandler {
+
+ NegotiateAuthentication() {
+ super(proxyAddress);
+ }
+
+ @Override
+ public String getName() {
+ return "Negotiate";
+ }
+
+ @Override
+ public String getToken() {
+ return getName() + ' ' + Base64.getEncoder().encodeToString(token);
+ }
+
+ @Override
+ protected GSSContext createContext() throws Exception {
+ return GssApiMechanisms.createContext(GssApiMechanisms.SPNEGO, GssApiMechanisms.getCanonicalName(proxyAddress));
+ }
+
+ @Override
+ protected byte[] extractToken(AuthenticationChallenge input) {
+ String received = input.getToken();
+ if (received == null) {
+ return new byte[0];
+ }
+ return Base64.getDecoder().decode(received);
+ }
+
+ }
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/Socks5ProxyConnector.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/Socks5ProxyConnector.java
new file mode 100644
index 000000000..d38956d6f
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/Socks5ProxyConnector.java
@@ -0,0 +1,559 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.text.MessageFormat;
+import java.util.Arrays;
+import java.util.function.Function;
+import java.util.logging.Level;
+
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.common.SshConstants;
+import org.apache.sshd.common.forward.SocksConstants.Socks5;
+import org.apache.sshd.common.io.IoWriteFuture;
+import org.apache.sshd.common.util.Readable;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.common.util.buffer.BufferException;
+import org.apache.sshd.common.util.buffer.BufferUtils;
+import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
+import org.apache.sshd.common.util.io.functors.IOFunction;
+import org.apache.sshd.common.util.logging.LoggingUtils;
+import org.apache.sshd.common.util.logging.SimplifiedLog;
+import org.ietf.jgss.GSSContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static java.nio.charset.StandardCharsets.US_ASCII;
+import static java.nio.charset.StandardCharsets.UTF_8;
+
+/**
+ * A {@link AbstractProxyConnector} to connect through a SOCKS5 proxy.
+ *
+ * @see <a href="https://tools.ietf.org/html/rfc1928">RFC 1928</a>
+ */
+@SuppressWarnings("checkstyle:MethodCount")
+public class Socks5ProxyConnector extends AbstractProxyConnector {
+
+ private static final Logger LOG = LoggerFactory.getLogger(Socks5ProxyConnector.class);
+
+ private static final SimplifiedLog SIMPLE = LoggingUtils.wrap(LOG);
+
+ /**
+ * Authentication methods for SOCKS5.
+ *
+ * @see <a href= "https://www.iana.org/assignments/socks-methods/socks-methods.xhtml">SOCKS Methods, IANA.org</a>
+ */
+ private enum SocksAuthenticationMethod {
+
+ ANONYMOUS(0),
+ GSSAPI(1),
+ PASSWORD(2),
+ // CHALLENGE_HANDSHAKE(3),
+ // CHALLENGE_RESPONSE(5),
+ // SSL(6),
+ // NDS(7),
+ // MULTI_AUTH(8),
+ // JSON(9),
+ NONE_ACCEPTABLE(0xFF);
+
+ private final byte value;
+
+ SocksAuthenticationMethod(int value) {
+ this.value = (byte) value;
+ }
+
+ public byte getValue() {
+ return value;
+ }
+ }
+
+ private enum ProtocolState {
+ NONE,
+
+ INIT {
+ @Override
+ public void handleMessage(Socks5ProxyConnector connector, Buffer data) throws Exception {
+ connector.versionCheck(data.getByte());
+ SocksAuthenticationMethod authMethod = connector.getAuthMethod(data.getByte());
+ switch (authMethod) {
+ case ANONYMOUS:
+ connector.sendConnectInfo();
+ break;
+ case PASSWORD:
+ connector.doPasswordAuth();
+ break;
+ case GSSAPI:
+ connector.doGssApiAuth();
+ break;
+ default:
+ throw new IOException("Cannot authenticate at SOCKS proxy " + connector.proxyAddress);
+ }
+ }
+ },
+
+ AUTHENTICATING {
+ @Override
+ public void handleMessage(Socks5ProxyConnector connector, Buffer data) throws Exception {
+ connector.authStep(data);
+ }
+ },
+
+ CONNECTING {
+ @Override
+ public void handleMessage(Socks5ProxyConnector connector, 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);
+ }
+ }
+ },
+
+ CONNECTED,
+
+ FAILED;
+
+ public void handleMessage(Socks5ProxyConnector connector, Buffer data) throws Exception {
+ throw new IOException(MessageFormat.format("Unexpected reply from SOCKS proxy {0}: {1}", connector.proxyAddress,
+ BufferUtils.toHex(data.array())));
+ }
+ }
+
+ private ProtocolState state;
+
+ private AuthenticationHandler<Buffer, Buffer> authenticator;
+
+ private GSSContext context;
+
+ private byte[] authenticationProposals;
+
+ /**
+ * Creates a new {@link Socks5ProxyConnector}. The connector supports anonymous connections as well as
+ * username-password or Kerberos5 (GSS-API) authentication.
+ *
+ * @param proxy {@link ProxyData} of the proxy we're connected to
+ * @param remoteAddress {@link InetSocketAddress} of the target server to connect to
+ * @param send a function to send data and returning an {@link IoWriteFuture}
+ * @param passwordAuth a function to query the user for proxy credentials, if needed, and returning a
+ * {@link PasswordAuthentication}
+ */
+ public Socks5ProxyConnector(ProxyData proxy, InetSocketAddress remoteAddress, IOFunction<Buffer, IoWriteFuture> send,
+ Function<InetSocketAddress, PasswordAuthentication> passwordAuth) {
+ super(proxy, remoteAddress, send, passwordAuth);
+ this.state = ProtocolState.NONE;
+ }
+
+ @Override
+ public void start() throws IOException {
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("SOCKS5 starting connection to {}", remoteAddress);
+ }
+ // Send the initial request
+ Buffer buffer = new ByteArrayBuffer(5, false);
+ buffer.putByte(Socks5.VERSION);
+ context = getGSSContext(remoteAddress);
+ authenticationProposals = getAuthenticationProposals();
+ buffer.putByte((byte) authenticationProposals.length);
+ buffer.putRawBytes(authenticationProposals);
+ state = ProtocolState.INIT;
+ write(buffer);
+ }
+
+ private byte[] getAuthenticationProposals() {
+ byte[] proposals = new byte[3];
+ int i = 0;
+ proposals[i++] = SocksAuthenticationMethod.ANONYMOUS.getValue();
+ proposals[i++] = SocksAuthenticationMethod.PASSWORD.getValue();
+ if (context != null) {
+ proposals[i++] = SocksAuthenticationMethod.GSSAPI.getValue();
+ }
+ if (i == proposals.length) {
+ return proposals;
+ }
+ return Arrays.copyOf(proposals, i);
+ }
+
+ private void sendConnectInfo() throws IOException {
+ GssApiMechanisms.closeContextSilently(context);
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("SOCKS5 authenticated, requesting connection to {}", remoteAddress);
+ }
+
+ byte[] rawAddress = getRawAddress(remoteAddress);
+ byte[] remoteName = null;
+ byte type;
+ int length = 0;
+ if (rawAddress == null) {
+ remoteName = remoteAddress.getHostString().getBytes(US_ASCII);
+ if (remoteName == null || remoteName.length == 0) {
+ throw new IOException("No remote host name");
+ } else if (remoteName.length > 255) {
+ // Should not occur; host names must not be longer than 255 US_ASCII characters.
+ throw new IOException(
+ "Proxy host name too long for SOCKS (at most 255 characters): " + remoteAddress.getHostString());
+ }
+ type = Socks5.ADDRESS_FQDN;
+ length = remoteName.length + 1;
+ } else {
+ length = rawAddress.length;
+ type = length == 4 ? Socks5.ADDRESS_IPV4 : Socks5.ADDRESS_IPV6;
+ }
+ Buffer buffer = new ByteArrayBuffer(4 + length + 2, false);
+ buffer.putByte(Socks5.VERSION);
+ buffer.putByte(Socks5.CMD_CONNECT);
+ buffer.putByte((byte) 0); // Reserved
+ buffer.putByte(type);
+ if (remoteName != null) {
+ buffer.putByte((byte) remoteName.length);
+ buffer.putRawBytes(remoteName);
+ } else {
+ buffer.putRawBytes(rawAddress);
+ }
+ int port = remoteAddress.getPort();
+ if (port <= 0) {
+ port = SshConstants.DEFAULT_PORT;
+ }
+ buffer.putByte((byte) ((port >> 8) & 0xFF));
+ buffer.putByte((byte) (port & 0xFF));
+ state = ProtocolState.CONNECTING;
+ write(buffer);
+ }
+
+ private void doPasswordAuth() throws Exception {
+ GssApiMechanisms.closeContextSilently(context);
+ authenticator = new SocksBasicAuthentication();
+ startAuth();
+ }
+
+ private void doGssApiAuth() throws Exception {
+ authenticator = new SocksGssApiAuthentication();
+ startAuth();
+ }
+
+ @Override
+ public void close() {
+ super.close();
+ AuthenticationHandler<?, ?> handler = authenticator;
+ authenticator = null;
+ if (handler != null) {
+ handler.close();
+ }
+ }
+
+ private void startAuth() throws Exception {
+ Buffer buffer = null;
+ try {
+ authenticator.setParams(null);
+ authenticator.start();
+ buffer = authenticator.getToken();
+ if (buffer == null) {
+ throw new IOException("No data for authenticating at proxy " + proxyAddress);
+ }
+ state = ProtocolState.AUTHENTICATING;
+ write(buffer);
+ } finally {
+ if (buffer != null) {
+ buffer.clear(true);
+ }
+ }
+ }
+
+ private void authStep(Buffer input) throws Exception {
+ authenticator.setParams(input);
+ authenticator.process();
+ Buffer buffer = authenticator.getToken();
+ if (buffer != null) {
+ write(buffer).addListener(f -> buffer.clear(true));
+ }
+ if (authenticator.isDone()) {
+ sendConnectInfo();
+ }
+ }
+
+ private void establishConnection(Buffer data) throws IOException {
+ byte reply = data.getByte();
+ switch (reply) {
+ case Socks5.REPLY_SUCCESS:
+ // Server also returns the "bind" address it uses, but we don't care. Skip it properly, though:
+ try {
+ reply = data.getByte();
+ if (reply != 0) {
+ LOG.warn("SOCKS5 proxy for connection to {} returned success with reserved byte != 0", remoteAddress);
+ }
+ skipAddress(data);
+ int port = data.getUShort();
+ if (port <= 0) {
+ LOG.warn("SOCKS5 proxy for connection to {} returned success with invalid bind port {}", remoteAddress,
+ Integer.toString(port));
+ }
+ } catch (BufferException e) {
+ data.rpos(0);
+ LOG.warn("SOCKS5 proxy for connection to {} returned malformed success reply; got {}", remoteAddress,
+ e.toString());
+ BufferUtils.dumpHex(SIMPLE, Level.WARNING, "remaining", BufferUtils.DEFAULT_HEX_SEPARATOR, 32, data.array(),
+ data.rpos(), data.available());
+ // Consume the whole buffer
+ data.rpos(data.wpos());
+ }
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("SOCKS5 connected to {}", remoteAddress);
+ }
+ state = ProtocolState.CONNECTED;
+ done = true;
+ return;
+ case Socks5.REPLY_FAILURE:
+ throw new IOException("Tunneling failed for proxy " + proxyAddress);
+ case Socks5.REPLY_FORBIDDEN:
+ throw new IOException(
+ MessageFormat.format("Forbidden tunnel at proxy {0} to {1}", proxyAddress, remoteAddress));
+ case Socks5.REPLY_NETWORK_UNREACHABLE:
+ throw new IOException(MessageFormat.format("Network unreachable at proxy {0} for tunnel to {1}", proxyAddress,
+ remoteAddress));
+ case Socks5.REPLY_HOST_UNREACHABLE:
+ throw new IOException(
+ MessageFormat.format("Host unreachable at proxy {0} for tunnel to {1}", proxyAddress, remoteAddress));
+ case Socks5.REPLY_CONNECTION_REFUSED:
+ throw new IOException(
+ MessageFormat.format("Connection refused at proxy {0} for tunnel to {1}", proxyAddress, remoteAddress));
+ case Socks5.REPLY_TTL_EXPIRED:
+ throw new IOException(
+ MessageFormat.format("TTL expired at proxy {0} for tunnel to {1}", proxyAddress, remoteAddress));
+ case Socks5.REPLY_COMMAND_UNSUPPORTED:
+ throw new IOException("Unsupported command at proxy " + proxyAddress);
+ case Socks5.REPLY_ADDRESS_UNSUPPORTED:
+ throw new IOException("Unsupported address at proxy " + proxyAddress);
+ default:
+ throw new IOException("Unspecified failure at proxy " + proxyAddress);
+ }
+ }
+
+ private void skipAddress(Buffer data) {
+ int skip = -1;
+ int type = data.getUByte();
+ switch (type) {
+ case Socks5.ADDRESS_IPV4:
+ skip = 4;
+ break;
+ case Socks5.ADDRESS_IPV6:
+ skip = 16;
+ break;
+ case Socks5.ADDRESS_FQDN:
+ skip = data.getUByte();
+ break;
+ default:
+ throw new BufferException("Invalid bind address type " + type);
+ }
+ if (data.available() < skip) {
+ throw new BufferException("Not enough data; need " + skip + ", have " + data.available());
+ }
+ data.rpos(data.rpos() + skip);
+ }
+
+ @Override
+ public Buffer received(Readable buffer) throws Exception {
+ try {
+ // Dispatch according to protocol state
+ ByteArrayBuffer data = new ByteArrayBuffer(buffer.available(), false);
+ data.putBuffer(buffer);
+ state.handleMessage(this, data);
+ return data;
+ } catch (Exception e) {
+ state = ProtocolState.FAILED;
+ if (authenticator != null) {
+ authenticator.close();
+ authenticator = null;
+ }
+ done = true;
+ throw e;
+ }
+ }
+
+ private void versionCheck(byte version) throws IOException {
+ if (version != Socks5.VERSION) {
+ throw new IOException("Unexpected SOCK version " + (version & 0xFF));
+ }
+ }
+
+ private SocksAuthenticationMethod getAuthMethod(byte value) {
+ if (value != SocksAuthenticationMethod.NONE_ACCEPTABLE.getValue()) {
+ for (byte proposed : authenticationProposals) {
+ if (proposed == value) {
+ for (SocksAuthenticationMethod method : SocksAuthenticationMethod.values()) {
+ if (method.getValue() == value) {
+ return method;
+ }
+ }
+ break;
+ }
+ }
+ }
+ return SocksAuthenticationMethod.NONE_ACCEPTABLE;
+ }
+
+ private static byte[] getRawAddress(InetSocketAddress address) {
+ InetAddress ipAddress = GssApiMechanisms.resolve(address);
+ return ipAddress == null ? null : ipAddress.getAddress();
+ }
+
+ private static GSSContext getGSSContext(InetSocketAddress address) {
+ if (!GssApiMechanisms.getSupportedMechanisms().contains(GssApiMechanisms.KERBEROS_5)) {
+ return null;
+ }
+ return GssApiMechanisms.createContext(GssApiMechanisms.KERBEROS_5, GssApiMechanisms.getCanonicalName(address));
+ }
+
+ /**
+ * @see <a href="https://tools.ietf.org/html/rfc1929">RFC 1929</a>
+ */
+ private class SocksBasicAuthentication extends BasicAuthentication<Buffer, Buffer> {
+
+ private static final byte SOCKS_BASIC_PROTOCOL_VERSION = 1;
+
+ private static final byte SOCKS_BASIC_AUTH_SUCCESS = 0;
+
+ SocksBasicAuthentication() {
+ super(proxyAddress, proxyUser, proxyPassword);
+ }
+
+ @Override
+ public void process() throws Exception {
+ // Retries impossible. RFC 1929 specifies that the server MUST
+ // close the connection if authentication is unsuccessful.
+ done = true;
+ if (params.getByte() != SOCKS_BASIC_PROTOCOL_VERSION || params.getByte() != SOCKS_BASIC_AUTH_SUCCESS) {
+ throw new IOException("SOCKS BASIC authentication failed at proxy " + proxy);
+ }
+ }
+
+ @Override
+ protected PasswordAuthentication getCredentials() {
+ return passwordAuthentication();
+ }
+
+ @Override
+ public Buffer getToken() throws IOException {
+ if (done) {
+ return null;
+ }
+ try {
+ byte[] rawUser = user.getBytes(UTF_8);
+ if (rawUser.length > 255) {
+ throw new IOException(MessageFormat.format("User name too long for proxy {0}: {1} bytes (max 255): {2}",
+ proxy, Integer.toString(rawUser.length), user));
+ }
+
+ if (password.length > 255) {
+ throw new IOException(MessageFormat.format("Password too long for proxy {0}: {1} bytes (max 255)", proxy,
+ Integer.toString(password.length)));
+ }
+ ByteArrayBuffer buffer = new ByteArrayBuffer(3 + rawUser.length + password.length, false);
+ buffer.putByte(SOCKS_BASIC_PROTOCOL_VERSION);
+ buffer.putByte((byte) rawUser.length);
+ buffer.putRawBytes(rawUser);
+ buffer.putByte((byte) password.length);
+ buffer.putRawBytes(password);
+ return buffer;
+ } finally {
+ clearPassword();
+ done = true;
+ }
+ }
+ }
+
+ /**
+ * @see <a href="https://tools.ietf.org/html/rfc1961">RFC 1961</a>
+ */
+ private class SocksGssApiAuthentication extends GssApiAuthentication<Buffer, Buffer> {
+
+ private static final byte SOCKS5_GSSAPI_VERSION = 1;
+
+ private static final byte SOCKS5_GSSAPI_TOKEN = 1;
+
+ private static final int SOCKS5_GSSAPI_FAILURE = 0xFF;
+
+ SocksGssApiAuthentication() {
+ super(proxyAddress);
+ }
+
+ @Override
+ protected GSSContext createContext() throws Exception {
+ return context;
+ }
+
+ @Override
+ public Buffer getToken() throws IOException {
+ if (token == null) {
+ return null;
+ }
+ Buffer buffer = new ByteArrayBuffer(4 + token.length, false);
+ buffer.putByte(SOCKS5_GSSAPI_VERSION);
+ buffer.putByte(SOCKS5_GSSAPI_TOKEN);
+ buffer.putByte((byte) ((token.length >> 8) & 0xFF));
+ buffer.putByte((byte) (token.length & 0xFF));
+ buffer.putRawBytes(token);
+ return buffer;
+ }
+
+ @Override
+ protected byte[] extractToken(Buffer input) throws Exception {
+ if (context == null) {
+ return null;
+ }
+ int version = input.getUByte();
+ if (version != SOCKS5_GSSAPI_VERSION) {
+ throw new IOException(MessageFormat.format("Wrong GSS-API version at SOCKS proxy {0}: {1}", proxy,
+ Integer.toString(version)));
+ }
+ int msgType = input.getUByte();
+ if (msgType == SOCKS5_GSSAPI_FAILURE) {
+ throw new IOException(MessageFormat.format("SOCKS Proxy {0} reported GSS-API failure", proxy));
+ } else if (msgType != SOCKS5_GSSAPI_TOKEN) {
+ throw new IOException(MessageFormat.format("Unknown GSS-API message {1} from SOCKS proxy {0}", proxy,
+ Integer.toHexString(msgType & 0xFF)));
+ }
+ if (input.available() >= 2) {
+ int length = (input.getUByte() << 8) + input.getUByte();
+ if (input.available() >= length) {
+ byte[] value = new byte[length];
+ if (length > 0) {
+ input.getRawBytes(value);
+ }
+ return value;
+ }
+ }
+ throw new IOException("Message too short from proxy" + proxy);
+ }
+ }
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/StatusLine.java b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/StatusLine.java
new file mode 100644
index 000000000..627d385d3
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/proxy/StatusLine.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.session.proxy;
+
+/**
+ * A very simple representation of a HTTP status line.
+ */
+public class StatusLine {
+
+ private final String version;
+
+ private final int resultCode;
+
+ private final String reason;
+
+ /**
+ * Create a new {@link StatusLine} with the given response code and reason string.
+ *
+ * @param version the version string (normally "HTTP/1.1" or "HTTP/1.0")
+ * @param resultCode the HTTP response code (200, 401, etc.)
+ * @param reason the reason phrase for the code
+ */
+ public StatusLine(String version, int resultCode, String reason) {
+ this.version = version;
+ this.resultCode = resultCode;
+ this.reason = reason;
+ }
+
+ /**
+ * Retrieves the version string.
+ *
+ * @return the version string
+ */
+ public String getVersion() {
+ return version;
+ }
+
+ /**
+ * Retrieves the HTTP response code.
+ *
+ * @return the code
+ */
+ public int getResultCode() {
+ return resultCode;
+ }
+
+ /**
+ * Retrieves the HTTP reason phrase.
+ *
+ * @return the reason
+ */
+ public String getReason() {
+ return reason;
+ }
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/forward/SocksConstants.java b/sshd-core/src/main/java/org/apache/sshd/common/forward/SocksConstants.java
new file mode 100644
index 000000000..b29e663c3
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/common/forward/SocksConstants.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.common.forward;
+
+/**
+ * SOCKS constants.
+ */
+public final class SocksConstants {
+
+ public static final class Socks4 {
+
+ public static final byte VERSION = 4;
+
+ public static final byte CMD_CONNECT = 1;
+
+ public static final byte REPLY_SUCCESS = (byte) 90;
+
+ public static final byte REPLY_FAILURE = (byte) 91;
+
+ public static final byte REPLY_HOST_UNREACHABLE = (byte) 92;
+
+ public static final byte REPLY_WRONG_USER = (byte) 93;
+
+ private Socks4() {
+ // No instantiation
+ }
+ }
+
+ public static final class Socks5 {
+
+ public static final byte VERSION = 5;
+
+ public static final byte CMD_CONNECT = 1;
+ // BIND = 2, UPD_ASSOCIATE = 3
+
+ // Address types
+
+ public static final byte ADDRESS_IPV4 = 1;
+
+ public static final byte ADDRESS_FQDN = 3;
+
+ public static final byte ADDRESS_IPV6 = 4;
+
+ // Reply codes
+
+ public static final byte REPLY_SUCCESS = 0;
+
+ public static final byte REPLY_FAILURE = 1;
+
+ public static final byte REPLY_FORBIDDEN = 2;
+
+ public static final byte REPLY_NETWORK_UNREACHABLE = 3;
+
+ public static final byte REPLY_HOST_UNREACHABLE = 4;
+
+ public static final byte REPLY_CONNECTION_REFUSED = 5;
+
+ public static final byte REPLY_TTL_EXPIRED = 6;
+
+ public static final byte REPLY_COMMAND_UNSUPPORTED = 7;
+
+ public static final byte REPLY_ADDRESS_UNSUPPORTED = 8;
+
+ private Socks5() {
+ // No instantiation
+ }
+ }
+
+ private SocksConstants() {
+ // No instatiation
+ }
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/forward/SocksProxy.java b/sshd-core/src/main/java/org/apache/sshd/common/forward/SocksProxy.java
index 46880fb34..2534db1a6 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/forward/SocksProxy.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/forward/SocksProxy.java
@@ -20,11 +20,14 @@ package org.apache.sshd.common.forward;
import java.io.Closeable;
import java.io.IOException;
+import java.net.InetSocketAddress;
+import java.net.SocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.sshd.client.future.OpenFuture;
import org.apache.sshd.common.SshException;
+import org.apache.sshd.common.channel.LocalWindow;
import org.apache.sshd.common.channel.StreamingChannel.Streaming;
import org.apache.sshd.common.io.IoHandler;
import org.apache.sshd.common.io.IoSession;
@@ -71,9 +74,9 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
Proxy proxy = proxies.get(session);
if (proxy == null) {
int version = buffer.getUByte();
- if (version == 0x04) {
+ if (version == SocksConstants.Socks4.VERSION) {
proxy = new Socks4(session);
- } else if (version == 0x05) {
+ } else if (version == SocksConstants.Socks5.VERSION) {
proxy = new Socks5(session);
} else {
throw new IllegalStateException("Unsupported version: " + version);
@@ -91,7 +94,8 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
session.close(false);
}
- public abstract static class Proxy implements Closeable {
+ public abstract class Proxy implements Closeable {
+
protected IoSession session;
protected TcpipClientChannel channel;
@@ -116,7 +120,33 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
}
protected int getUShort(Buffer buffer) {
- return (getUByte(buffer) << Byte.SIZE) + getUByte(buffer);
+ return buffer.getUShort();
+ }
+
+ protected void sendReply(Buffer message, boolean success, LocalWindow window, long windowSize) {
+ try {
+ session.writeBuffer(message);
+ } catch (IOException e) {
+ log.error("Failed ({}) to send channel open response for {}: {}", e.getClass().getSimpleName(), channel,
+ e.getMessage());
+ if (success) {
+ service.unregisterChannel(channel);
+ channel.close(true);
+ }
+ throw new IllegalStateException("Failed to send packet", e);
+ }
+ if (success) {
+ session.resumeRead();
+ // Open the channel window: we're ready to accept data now.
+ try {
+ window.release(windowSize);
+ } catch (IOException e) {
+ log.error("Could not open channel window to {} on channel {}: {}", windowSize, channel, e);
+ service.unregisterChannel(channel);
+ channel.close(true);
+ throw new IllegalStateException("Failed to open window", e);
+ }
+ }
}
}
@@ -133,7 +163,7 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
protected void onMessage(Buffer buffer) throws IOException {
if (channel == null) {
int cmd = buffer.getUByte();
- if (cmd != 1) {
+ if (cmd != SocksConstants.Socks4.CMD_CONNECT) {
throw new IllegalStateException("Unsupported socks command: " + cmd);
}
int port = getUShort(buffer);
@@ -155,14 +185,18 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
channel.setStreaming(Streaming.Async);
session.suspendRead();
service.registerChannel(channel);
- channel.open().addListener(this::onChannelOpened);
+ // Open the channel, but don't accept input data yet!
+ LocalWindow window = channel.getLocalWindow();
+ long windowSize = window.getSize();
+ window.consume(windowSize);
+ channel.open().addListener(f -> onChannelOpened(f, window, windowSize));
} else {
super.onMessage(buffer);
}
}
@SuppressWarnings("synthetic-access")
- protected void onChannelOpened(OpenFuture future) {
+ protected void onChannelOpened(OpenFuture future, LocalWindow window, long windowSize) {
session.resumeRead();
Buffer buffer = new ByteArrayBuffer(Long.SIZE, false);
buffer.putByte((byte) 0x00);
@@ -170,9 +204,9 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
if (t != null) {
service.unregisterChannel(channel);
channel.close(true);
- buffer.putByte((byte) 0x5b);
+ buffer.putByte(SocksConstants.Socks4.REPLY_FAILURE);
} else {
- buffer.putByte((byte) 0x5a);
+ buffer.putByte(SocksConstants.Socks4.REPLY_SUCCESS);
}
buffer.putByte((byte) 0x00);
buffer.putByte((byte) 0x00);
@@ -180,14 +214,7 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
buffer.putByte((byte) 0x00);
buffer.putByte((byte) 0x00);
buffer.putByte((byte) 0x00);
- try {
- session.writeBuffer(buffer);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- log.error("Failed ({}) to send channel open packet for {}: {}", e.getClass().getSimpleName(), channel,
- e.getMessage());
- throw new IllegalStateException("Failed to send packet", e);
- }
+ sendReply(buffer, t == null, window, windowSize);
}
protected String getNTString(Buffer buffer) {
@@ -203,8 +230,8 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
* @see <A HREF="https://en.wikipedia.org/wiki/SOCKS#SOCKS5">SOCKS5</A>
*/
public class Socks5 extends Proxy {
+
private byte[] authMethods;
- private Buffer response;
public Socks5(IoSession session) {
super(session);
@@ -223,7 +250,7 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
foundNoAuth |= authMethods[i] == 0;
}
buffer = new ByteArrayBuffer(Byte.SIZE, false);
- buffer.putByte((byte) 0x05);
+ buffer.putByte(SocksConstants.Socks5.VERSION);
buffer.putByte((byte) (foundNoAuth ? 0x00 : 0xFF));
session.writeBuffer(buffer);
if (!foundNoAuth) {
@@ -232,32 +259,29 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
log.debug("Received socks5 greeting");
}
} else if (channel == null) {
- response = buffer;
int version = getUByte(buffer);
- if (version != 0x05) {
+ if (version != SocksConstants.Socks5.VERSION) {
throw new IllegalStateException("Unexpected version: " + version);
}
int cmd = buffer.getUByte();
- if (cmd != 1) { // establish a TCP/IP stream connection
+ if (cmd != SocksConstants.Socks5.CMD_CONNECT) { // establish a TCP/IP stream connection
throw new IllegalStateException("Unsupported socks command: " + cmd);
}
int res = buffer.getUByte();
- if (res != 0) {
- if (debugEnabled) {
- log.debug("No zero reserved value: {}", res);
- }
+ if (res != 0 && debugEnabled) {
+ log.debug("No zero reserved value: {}", res);
}
int type = buffer.getUByte();
String host;
- if (type == 0x01) {
+ if (type == SocksConstants.Socks5.ADDRESS_IPV4) {
host = Integer.toString(getUByte(buffer)) + "."
+ Integer.toString(getUByte(buffer)) + "."
+ Integer.toString(getUByte(buffer)) + "."
+ Integer.toString(getUByte(buffer));
- } else if (type == 0x03) {
+ } else if (type == SocksConstants.Socks5.ADDRESS_FQDN) {
host = getBLString(buffer);
- } else if (type == 0x04) {
+ } else if (type == SocksConstants.Socks5.ADDRESS_IPV6) {
host = Integer.toHexString(getUShort(buffer)) + ":"
+ Integer.toHexString(getUShort(buffer)) + ":"
+ Integer.toHexString(getUShort(buffer)) + ":"
@@ -278,7 +302,11 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
channel.setStreaming(Streaming.Async);
session.suspendRead();
service.registerChannel(channel);
- channel.open().addListener(this::onChannelOpened);
+ // Open the channel, but don't accept input data yet!
+ LocalWindow window = channel.getLocalWindow();
+ long windowSize = window.getSize();
+ window.consume(windowSize);
+ channel.open().addListener(f -> onChannelOpened(f, window, windowSize));
} else {
if (debugEnabled) {
log.debug("Received socks5 connection message");
@@ -288,27 +316,35 @@ public class SocksProxy extends AbstractCloseable implements IoHandler {
}
@SuppressWarnings("synthetic-access")
- protected void onChannelOpened(OpenFuture future) {
- session.resumeRead();
- int wpos = response.wpos();
- response.rpos(0);
- response.wpos(1);
+ protected void onChannelOpened(OpenFuture future, LocalWindow window, long windowSize) {
+ Buffer response = new ByteArrayBuffer(2);
+ response.putByte(SocksConstants.Socks5.VERSION);
Throwable t = future.getException();
if (t != null) {
service.unregisterChannel(channel);
channel.close(true);
- response.putByte((byte) 0x01);
+ response.putByte(SocksConstants.Socks5.REPLY_FAILURE);
} else {
- response.putByte((byte) 0x00);
+ response.putByte(SocksConstants.Socks5.REPLY_SUCCESS);
}
- response.wpos(wpos);
- try {
- session.writeBuffer(response);
- } catch (IOException e) {
- log.error("Failed ({}) to send channel open response for {}: {}", e.getClass().getSimpleName(), channel,
- e.getMessage());
- throw new IllegalStateException("Failed to send packet", e);
+ response.putByte((byte) 0x00); // reserved
+ SocketAddress bound = session.getAcceptanceAddress();
+ if (bound instanceof InetSocketAddress) {
+ byte[] ip = ((InetSocketAddress) bound).getAddress().getAddress();
+ if (ip.length == 4) {
+ response.putByte(SocksConstants.Socks5.ADDRESS_IPV4);
+ } else {
+ response.putByte(SocksConstants.Socks5.ADDRESS_IPV6);
+ }
+ response.putRawBytes(ip);
+ response.putShort(((InetSocketAddress) bound).getPort());
+ } else {
+ // Just fill in some dummy values.
+ response.putByte(SocksConstants.Socks5.ADDRESS_IPV4);
+ response.putLong(0);
+ response.putShort(0);
}
+ sendReply(response, t == null, window, windowSize);
}
protected String getBLString(Buffer buffer) {
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/filters/IdentFilter.java b/sshd-core/src/main/java/org/apache/sshd/common/session/filters/IdentFilter.java
index 05f853156..12d0d7bf9 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/filters/IdentFilter.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/filters/IdentFilter.java
@@ -38,6 +38,8 @@ import org.apache.sshd.common.util.Readable;
import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
import org.apache.sshd.core.CoreModuleProperties;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
* A filter for sending the identification string before the first outgoing packet, and for receiving the peer's
@@ -45,6 +47,8 @@ import org.apache.sshd.core.CoreModuleProperties;
*/
public class IdentFilter extends IoFilter {
+ private static final Logger LOG = LoggerFactory.getLogger(IdentFilter.class);
+
private static final String CRLF = "\r\n";
private DefaultIoWriteFuture received = new DefaultIoWriteFuture("IdentReceived", null);
@@ -114,14 +118,19 @@ public class IdentFilter extends IoFilter {
// Just pass on the message.
owner().passOn(message);
} else {
+ int msgSize = message.available();
buffer.putBuffer(message);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("received({}) in {}, now at {}", properties, msgSize, buffer.available());
+ }
List<String> lines = identHandler.readIdentification(buffer);
haveIdent = !GenericUtils.isEmpty(lines);
if (haveIdent) {
- listeners.forEach(listener -> listener.ident(true, lines.get(lines.size() - 1)));
- buffer.compact();
+ String ident = lines.get(lines.size() - 1);
+ listeners.forEach(listener -> listener.ident(true, ident));
received.setValue(Boolean.TRUE);
if (buffer.available() > 0) {
+ buffer.compact();
owner().passOn(buffer);
}
readHandler.set(null);
@@ -202,10 +211,13 @@ public class IdentFilter extends IoFilter {
result.setValue(msgSent.isWritten() ? Boolean.TRUE : msgSent.getException());
});
} catch (IOException e) {
+ LOG.error("sendAfterIdent({}) {}", properties, e);
result.setValue(e);
}
} else {
- result.setValue(f.getException());
+ Throwable t = f.getException();
+ LOG.error("sendAfterIdent({}) {}", properties, t);
+ result.setValue(t);
}
});
return result;
@@ -218,6 +230,9 @@ public class IdentFilter extends IoFilter {
}
listeners.forEach(listener -> listener.ident(false, ident.get(ident.size() - 1)));
String myIdentification = ident.stream().collect(Collectors.joining(CRLF)) + CRLF;
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("getIdent({}) sending ident {}", properties, myIdentification);
+ }
return new ByteArrayBuffer(myIdentification.getBytes(StandardCharsets.UTF_8));
}
}
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/filters/PacketLoggingFilter.java b/sshd-core/src/main/java/org/apache/sshd/common/session/filters/PacketLoggingFilter.java
index 4272693c2..1af7abcb2 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/filters/PacketLoggingFilter.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/filters/PacketLoggingFilter.java
@@ -57,7 +57,12 @@ public class PacketLoggingFilter extends IoFilter {
@Override
public void handleMessage(Buffer message) throws Exception {
- if (LOG.isTraceEnabled()) {
+ if (LOG.isDebugEnabled()) {
+ int cmd = message.rawByte(message.rpos()) & 0xFF;
+ LOG.debug("receivePacket({}) packet #{} command={}[{}] len={}", session, crypt.getLastInputSequenceNumber(),
+ cmd, SshConstants.getCommandMessageName(cmd), message.available());
+ }
+ if (SIMPLE.isTraceEnabled()) {
message.dumpHex(SIMPLE, Level.FINEST,
"receivePacket(" + session + ") packet #" + crypt.getLastInputSequenceNumber(), session);
}
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/filters/kex/KexFilter.java b/sshd-core/src/main/java/org/apache/sshd/common/session/filters/kex/KexFilter.java
index a12be542d..4be26057e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/filters/kex/KexFilter.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/filters/kex/KexFilter.java
@@ -710,8 +710,8 @@ public class KexFilter extends IoFilter {
byte[] iC = isServer ? peerData.get() : myData.get();
KeyExchange k = kexFactory.createKeyExchange(session);
- k.init(vS, vC, iS, iC);
kex.set(k);
+ k.init(vS, vC, iS, iC);
synchronized (this) {
myProposalReady = null;
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/filters/kex/KexOutputHandler.java b/sshd-core/src/main/java/org/apache/sshd/common/session/filters/kex/KexOutputHandler.java
index e9dd3f90b..f8006e271 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/filters/kex/KexOutputHandler.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/filters/kex/KexOutputHandler.java
@@ -272,9 +272,14 @@ class KexOutputHandler implements OutputHandler {
//
// If so many packets are queued that flushing them triggers another KEX flushing stops
// and will be resumed at the end of the new KEX.
- if (kexDone && log.isDebugEnabled()) {
- log.debug("writeOrEnqueue({})[{}]: Queuing packet while flushing", filter.getSession(),
- SshConstants.getCommandMessageName(cmd));
+ if (log.isDebugEnabled()) {
+ if (kexDone) {
+ log.debug("writeOrEnqueue({})[{}]: Queuing packet while flushing", filter.getSession(),
+ SshConstants.getCommandMessageName(cmd));
+ } else {
+ log.debug("writeOrEnqueue({})[{}]: Queuing packet", filter.getSession(),
+ SshConstants.getCommandMessageName(cmd));
+ }
}
return enqueuePendingPacket(cmd, buffer);
}
diff --git a/sshd-core/src/main/java/org/apache/sshd/core/CoreModuleProperties.java b/sshd-core/src/main/java/org/apache/sshd/core/CoreModuleProperties.java
index eaee6459f..c777d0dbf 100644
--- a/sshd-core/src/main/java/org/apache/sshd/core/CoreModuleProperties.java
+++ b/sshd-core/src/main/java/org/apache/sshd/core/CoreModuleProperties.java
@@ -352,7 +352,7 @@ public final class CoreModuleProperties {
* Minimum NIO2 write wait timeout for a single outgoing packet - in milliseconds
*/
public static final Property<Duration> NIO2_MIN_WRITE_TIMEOUT
- = Property.duration("nio2-min-write-timeout", Duration.ofSeconds(30L));
+ = Property.duration("nio2-min-write-timeout", Duration.ofSeconds(30));
/**
* Key used to retrieve the value of the disconnect timeout which is used when a disconnection is attempted. If the
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ProxyHttpAuthIntegrationTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ProxyHttpAuthIntegrationTest.java
new file mode 100644
index 000000000..0103dfe1a
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ProxyHttpAuthIntegrationTest.java
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.net.Proxy;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.sshd.client.auth.keyboard.UserInteraction;
+import org.apache.sshd.client.future.AuthFuture;
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.common.SshException;
+import org.apache.sshd.common.util.GenericUtils;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.util.test.BaseTestSupport;
+import org.apache.sshd.util.test.CommandExecutionHelper;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.MountableFile;
+
+/**
+ * Test client connection through tinyproxy (HTTP CONNECT), requiring authentication.
+ */
+@Testcontainers
+@Tag("ContainerTestCase")
+class ProxyHttpAuthIntegrationTest extends BaseTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ProxyHttpAuthIntegrationTest.class);
+
+ @Container
+ static GenericContainer<?> proxy = new GenericContainer<>("vimagick/tinyproxy") //
+ .withCopyFileToContainer(MountableFile.forClasspathResource("org/apache/sshd/client/tinyproxy-auth.conf"),
+ "/etc/tinyproxy/tinyproxy.conf") //
+ .withExposedPorts(1080) //
+ .withLogConsumer(new Slf4jLogConsumer(LOG));
+
+ @Test
+ void httpProxy() throws Exception {
+ doTest(null, null, false, false);
+ }
+
+ @Test
+ void httpAuthProxyWrong() throws Exception {
+ doTest("foo", "bar".toCharArray(), true, false);
+ }
+
+ @Test
+ void httpAuthProxy() throws Exception {
+ doTest("httptester", "testhttp".toCharArray(), true, true);
+ }
+
+ @Test
+ void httpAuthProxyUi() throws Exception {
+ // HTTP CONNECT proxies may close the connection for basic auth. tinyproxy does.
+ doTest("httptester", "testhttp".toCharArray(), false, false);
+ }
+
+ private void doTest(String user, char[] password, boolean preSet, boolean expectSuccess) throws Exception {
+ Proxy proxyDescriptor = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getMappedPort(1080)));
+ ProxyData proxyData;
+ if (preSet) {
+ proxyData = new ProxyData(proxyDescriptor, user, password);
+ } else {
+ proxyData = new ProxyData(proxyDescriptor);
+ }
+ try (SshServer server = setupTestServer();
+ SshClient client = setupTestClient()) {
+ // setup server with an echo command
+ server.setCommandFactory((session, command) -> new CommandExecutionHelper(command) {
+
+ @Override
+ protected boolean handleCommandLine(String command) throws Exception {
+ OutputStream stdout = getOutputStream();
+ stdout.write(command.getBytes(StandardCharsets.US_ASCII));
+ stdout.flush();
+ return false;
+ }
+ });
+ server.start();
+ client.setProxyDataFactory(remoteAddress -> proxyData);
+ AtomicInteger passwordCalls = new AtomicInteger();
+ int expectedPasswordCalls = 0;
+ if (!preSet && !GenericUtils.isEmpty(user)) {
+ client.setUserInteraction(new UserInteraction() {
+
+ @Override
+ public String[] interactive(
+ ClientSession session, String name, String instruction, String lang,
+ String[] prompt, boolean[] echo) {
+ throw new IllegalStateException("interactive(" + session + ")[" + name + "] unexpected call");
+ }
+
+ @Override
+ public String getUpdatedPassword(ClientSession session, String prompt, String lang) {
+ throw new IllegalStateException("interactive(" + session + ")[" + prompt + "] unexpected call");
+ }
+
+ @Override
+ public PasswordAuthentication getProxyCredentials(ClientSession session, InetSocketAddress proxy) {
+ passwordCalls.incrementAndGet();
+ return new PasswordAuthentication(user, password);
+ }
+ });
+ expectedPasswordCalls = 1;
+ }
+ client.start();
+ // Connect through the proxy
+ try (ClientSession session = client.connect("user1", "host.docker.internal", server.getPort())
+ .verify(CONNECT_TIMEOUT).getSession()) {
+ session.addPasswordIdentity("user1");
+ AuthFuture future = session.auth();
+ if (expectSuccess) {
+ future.verify(AUTH_TIMEOUT);
+ } else {
+ assertThrows(SshException.class, () -> future.verify(AUTH_TIMEOUT));
+ return;
+ }
+ assertTrue(session.isAuthenticated());
+ testCommand(session, "ls -al");
+ }
+ assertEquals(expectedPasswordCalls, passwordCalls.get(), "Unexpected number of password calls");
+ }
+ }
+
+ private void testCommand(ClientSession session, String command) throws IOException {
+ String result;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream errors = new ByteArrayOutputStream();
+ session.executeRemoteCommand(command, out, errors, StandardCharsets.UTF_8);
+ result = out.toString();
+ assertEquals(command, result);
+ }
+
+}
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ProxyHttpIntegrationTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ProxyHttpIntegrationTest.java
new file mode 100644
index 000000000..14f4bf846
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ProxyHttpIntegrationTest.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.nio.charset.StandardCharsets;
+
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.util.test.BaseTestSupport;
+import org.apache.sshd.util.test.CommandExecutionHelper;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.MountableFile;
+
+/**
+ * Test client connection through tinyproxy (HTTP CONNECT), anonymous.
+ */
+@Testcontainers
+@Tag("ContainerTestCase")
+class ProxyHttpIntegrationTest extends BaseTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ProxyHttpIntegrationTest.class);
+
+ @Container
+ static GenericContainer<?> proxy = new GenericContainer<>("vimagick/tinyproxy") //
+ .withCopyFileToContainer(MountableFile.forClasspathResource("org/apache/sshd/client/tinyproxy.conf"),
+ "/etc/tinyproxy/tinyproxy.conf") //
+ .withExposedPorts(1080) //
+ .withLogConsumer(new Slf4jLogConsumer(LOG));
+
+ @Test
+ void httpProxy() throws Exception {
+ doTest(null, null);
+ }
+
+ @Test
+ void httpProxyAuth() throws Exception {
+ doTest("httptester", "testhttp".toCharArray());
+ }
+
+ private void doTest(String user, char[] password) throws Exception {
+ Proxy proxyDescriptor = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxy.getHost(), proxy.getMappedPort(1080)));
+ ProxyData proxyData = new ProxyData(proxyDescriptor, user, password);
+ try (SshServer server = setupTestServer();
+ SshClient client = setupTestClient()) {
+ // setup server with an echo command
+ server.setCommandFactory((session, command) -> new CommandExecutionHelper(command) {
+
+ @Override
+ protected boolean handleCommandLine(String command) throws Exception {
+ OutputStream stdout = getOutputStream();
+ stdout.write(command.getBytes(StandardCharsets.US_ASCII));
+ stdout.flush();
+ return false;
+ }
+ });
+ server.start();
+ client.setProxyDataFactory(remoteAddress -> proxyData);
+ client.start();
+ // Connect through the proxy
+ try (ClientSession session = client.connect("user1", "host.docker.internal", server.getPort())
+ .verify(CONNECT_TIMEOUT).getSession()) {
+ session.addPasswordIdentity("user1");
+ session.auth().verify(AUTH_TIMEOUT);
+ assertTrue(session.isAuthenticated());
+ testCommand(session, "ls -al");
+ }
+ }
+ }
+
+ private void testCommand(ClientSession session, String command) throws IOException {
+ String result;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream errors = new ByteArrayOutputStream();
+ session.executeRemoteCommand(command, out, errors, StandardCharsets.UTF_8);
+ result = out.toString();
+ assertEquals(command, result);
+ }
+
+}
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ProxyTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ProxyJumpTest.java
similarity index 99%
rename from sshd-core/src/test/java/org/apache/sshd/client/ProxyTest.java
rename to sshd-core/src/test/java/org/apache/sshd/client/ProxyJumpTest.java
index c6cbd616a..b9fc17aa8 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/ProxyTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ProxyJumpTest.java
@@ -61,7 +61,7 @@ import org.slf4j.LoggerFactory;
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
@TestMethodOrder(MethodName.class)
-class ProxyTest extends BaseTestSupport {
+class ProxyJumpTest extends BaseTestSupport {
protected final Logger logger = LoggerFactory.getLogger(getClass());
@@ -70,7 +70,7 @@ class ProxyTest extends BaseTestSupport {
private ClientSession proxySession;
- ProxyTest() {
+ ProxyJumpTest() {
super();
}
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ProxySocksAuthIntegrationTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ProxySocksAuthIntegrationTest.java
new file mode 100644
index 000000000..37c1bed65
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ProxySocksAuthIntegrationTest.java
@@ -0,0 +1,160 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.net.Proxy;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.sshd.client.auth.keyboard.UserInteraction;
+import org.apache.sshd.client.future.AuthFuture;
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.common.SshException;
+import org.apache.sshd.common.util.GenericUtils;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.util.test.BaseTestSupport;
+import org.apache.sshd.util.test.CommandExecutionHelper;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/**
+ * Test client connection through a SOCKS proxy requiring authentication.
+ */
+@Testcontainers
+@Tag("ContainerTestCase")
+class ProxySocksAuthIntegrationTest extends BaseTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ProxySocksAuthIntegrationTest.class);
+
+ @Container
+ static GenericContainer<?> proxy = new GenericContainer<>("serjs/go-socks5-proxy") //
+ .withEnv("PROXY_USER", "sockstester") //
+ .withEnv("PROXY_PASSWORD", "testsocks") //
+ .withExposedPorts(1080) //
+ .withLogConsumer(new Slf4jLogConsumer(LOG));
+
+ @Test
+ void socksProxy() throws Exception {
+ doTest(null, null, false, false);
+ }
+
+ @Test
+ void socksAuthProxyWrong() throws Exception {
+ doTest("foo", "bar".toCharArray(), true, false);
+ }
+
+ @Test
+ void socksAuthProxy() throws Exception {
+ doTest("sockstester", "testsocks".toCharArray(), true, true);
+ }
+
+ @Test
+ void socksAuthProxyUi() throws Exception {
+ doTest("sockstester", "testsocks".toCharArray(), false, true);
+ }
+
+ private void doTest(String user, char[] password, boolean preSet, boolean expectSuccess) throws Exception {
+ Proxy proxyDescriptor = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxy.getHost(), proxy.getMappedPort(1080)));
+ ProxyData proxyData;
+ if (preSet) {
+ proxyData = new ProxyData(proxyDescriptor, user, password);
+ } else {
+ proxyData = new ProxyData(proxyDescriptor);
+ }
+ try (SshServer server = setupTestServer();
+ SshClient client = setupTestClient()) {
+ // setup server with an echo command
+ server.setCommandFactory((session, command) -> new CommandExecutionHelper(command) {
+
+ @Override
+ protected boolean handleCommandLine(String command) throws Exception {
+ OutputStream stdout = getOutputStream();
+ stdout.write(command.getBytes(StandardCharsets.US_ASCII));
+ stdout.flush();
+ return false;
+ }
+ });
+ server.start();
+ client.setProxyDataFactory(remoteAddress -> proxyData);
+ AtomicInteger passwordCalls = new AtomicInteger();
+ int expectedPasswordCalls = 0;
+ if (!preSet && !GenericUtils.isEmpty(user)) {
+ client.setUserInteraction(new UserInteraction() {
+
+ @Override
+ public String[] interactive(
+ ClientSession session, String name, String instruction, String lang,
+ String[] prompt, boolean[] echo) {
+ throw new IllegalStateException("interactive(" + session + ")[" + name + "] unexpected call");
+ }
+
+ @Override
+ public String getUpdatedPassword(ClientSession session, String prompt, String lang) {
+ throw new IllegalStateException("interactive(" + session + ")[" + prompt + "] unexpected call");
+ }
+
+ @Override
+ public PasswordAuthentication getProxyCredentials(ClientSession session, InetSocketAddress proxy) {
+ passwordCalls.incrementAndGet();
+ return new PasswordAuthentication(user, password);
+ }
+ });
+ expectedPasswordCalls = 1;
+ }
+ client.start();
+ // Connect through the proxy
+ try (ClientSession session = client.connect("user1", "host.docker.internal", server.getPort())
+ .verify(CONNECT_TIMEOUT).getSession()) {
+ session.addPasswordIdentity("user1");
+ AuthFuture future = session.auth();
+ if (expectSuccess) {
+ future.verify(AUTH_TIMEOUT);
+ } else {
+ assertThrows(SshException.class, () -> future.verify(AUTH_TIMEOUT));
+ return;
+ }
+ assertTrue(session.isAuthenticated());
+ testCommand(session, "ls -al");
+ }
+ assertEquals(expectedPasswordCalls, passwordCalls.get(), "Unexpected number of password calls");
+ }
+ }
+
+ private void testCommand(ClientSession session, String command) throws IOException {
+ String result;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream errors = new ByteArrayOutputStream();
+ session.executeRemoteCommand(command, out, errors, StandardCharsets.UTF_8);
+ result = out.toString();
+ assertEquals(command, result);
+ }
+
+}
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ProxySocksIntegrationTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ProxySocksIntegrationTest.java
new file mode 100644
index 000000000..7754a38cb
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ProxySocksIntegrationTest.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.nio.charset.StandardCharsets;
+
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.util.test.BaseTestSupport;
+import org.apache.sshd.util.test.CommandExecutionHelper;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+
+/**
+ * Test client connection through an anonymous SOCKS proxy.
+ */
+@Testcontainers
+@Tag("ContainerTestCase")
+class ProxySocksIntegrationTest extends BaseTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ProxySocksIntegrationTest.class);
+
+ @Container
+ static GenericContainer<?> proxy = new GenericContainer<>("serjs/go-socks5-proxy") //
+ .withExposedPorts(1080) //
+ .withLogConsumer(new Slf4jLogConsumer(LOG));
+
+ @Test
+ void socksProxy() throws Exception {
+ doTest(null, null);
+ }
+
+ @Test
+ void socksProxyAuth() throws Exception {
+ doTest("sockstester", "testsocks".toCharArray());
+ }
+
+ private void doTest(String user, char[] password) throws Exception {
+ Proxy proxyDescriptor = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxy.getHost(), proxy.getMappedPort(1080)));
+ ProxyData proxyData = new ProxyData(proxyDescriptor, user, password);
+ try (SshServer server = setupTestServer();
+ SshClient client = setupTestClient()) {
+ // setup server with an echo command
+ server.setCommandFactory((session, command) -> new CommandExecutionHelper(command) {
+
+ @Override
+ protected boolean handleCommandLine(String command) throws Exception {
+ OutputStream stdout = getOutputStream();
+ stdout.write(command.getBytes(StandardCharsets.US_ASCII));
+ stdout.flush();
+ return false;
+ }
+ });
+ server.start();
+ client.setProxyDataFactory(remoteAddress -> proxyData);
+ client.start();
+ // Connect through the proxy
+ try (ClientSession session = client.connect("user1", "host.docker.internal", server.getPort())
+ .verify(CONNECT_TIMEOUT).getSession()) {
+ session.addPasswordIdentity("user1");
+ session.auth().verify(AUTH_TIMEOUT);
+ assertTrue(session.isAuthenticated());
+ testCommand(session, "ls -al");
+ }
+ }
+ }
+
+ private void testCommand(ClientSession session, String command) throws IOException {
+ String result;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream errors = new ByteArrayOutputStream();
+ session.executeRemoteCommand(command, out, errors, StandardCharsets.UTF_8);
+ result = out.toString();
+ assertEquals(command, result);
+ }
+
+}
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ProxySocksTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ProxySocksTest.java
new file mode 100644
index 000000000..6e5697143
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ProxySocksTest.java
@@ -0,0 +1,140 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.SocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.sshd.client.proxy.ProxyData;
+import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.client.session.forward.DynamicPortForwardingTracker;
+import org.apache.sshd.common.util.net.SshdSocketAddress;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.server.forward.AcceptAllForwardingFilter;
+import org.apache.sshd.server.session.ServerSession;
+import org.apache.sshd.util.test.BaseTestSupport;
+import org.apache.sshd.util.test.BogusPasswordAuthenticator;
+import org.apache.sshd.util.test.CommandExecutionHelper;
+import org.junit.jupiter.api.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Tests for using a SOCKS proxy.
+ */
+class ProxySocksTest extends BaseTestSupport {
+
+ private static final Logger LOG = LoggerFactory.getLogger(ProxySocksTest.class);
+
+ @Test
+ void proxy() throws Exception {
+ try (SshServer server = setupTestServer();
+ SshServer proxy = setupTestServer();
+ SshClient client = setupTestClient()) {
+ // setup proxy with a forwarding filter to allow the dynamic port forwarding
+ proxy.setForwardingFilter(AcceptAllForwardingFilter.INSTANCE);
+ proxy.start();
+
+ // setup server with an echo command
+ server.setCommandFactory((session, command) -> new CommandExecutionHelper(command) {
+
+ @Override
+ protected boolean handleCommandLine(String command) throws Exception {
+ OutputStream stdout = getOutputStream();
+ stdout.write(command.getBytes(StandardCharsets.US_ASCII));
+ stdout.flush();
+ return false;
+ }
+ });
+ AtomicReference<InetSocketAddress> clientAddress = new AtomicReference<>();
+
+ server.setPasswordAuthenticator(new BogusPasswordAuthenticator() {
+
+ @Override
+ public boolean authenticate(String username, String password, ServerSession session) {
+ SocketAddress rawFrom = session.getClientAddress();
+ if (!(rawFrom instanceof InetSocketAddress)) {
+ return false;
+ }
+ InetSocketAddress from = (InetSocketAddress) rawFrom;
+ InetSocketAddress clientDirect = clientAddress.get();
+ if (clientDirect == null || from.getPort() == clientDirect.getPort()) {
+ LOG.warn("Server got connection not through the proxy");
+ return false;
+ }
+ LOG.info("authenticate({}): Authenticating {} at server", session, username);
+ return super.authenticate(username, password, session);
+ };
+ });
+ server.start();
+
+ LOG.info("Proxy: " + proxy.getPort() + ", server: " + server.getPort());
+
+ // setup client
+ client.start();
+ try (ClientSession proxySession = client.connect("user1", TEST_LOCALHOST, proxy.getPort()).verify(CONNECT_TIMEOUT)
+ .getSession()) {
+ proxySession.addPasswordIdentity("user1");
+ proxySession.auth().verify(AUTH_TIMEOUT);
+ SshdSocketAddress anyLocal = new SshdSocketAddress("localhost", 0); // Let the system choose a port
+ try (DynamicPortForwardingTracker dynamic = proxySession.createDynamicPortForwardingTracker(anyLocal)) {
+ SshdSocketAddress socksAddress = dynamic.getBoundAddress();
+ LOG.info("SOCKS proxy listenting on {}", socksAddress);
+ Proxy proxyDescriptor = new Proxy(Proxy.Type.SOCKS,
+ new InetSocketAddress(socksAddress.getHostName(), socksAddress.getPort()));
+ client.setProxyDataFactory(remoteAddress -> {
+ if (SshdSocketAddress.isLoopback(remoteAddress.getAddress())
+ && server.getPort() == remoteAddress.getPort()) {
+ return new ProxyData(proxyDescriptor);
+ }
+ return null;
+ });
+ // Connect through the SOCKS proxy
+ try (ClientSession session = client.connect("user2", TEST_LOCALHOST, server.getPort())
+ .verify(CONNECT_TIMEOUT).getSession()) {
+ SocketAddress myAddress = session.getIoSession().getLocalAddress();
+ if (myAddress instanceof InetSocketAddress) {
+ clientAddress.set((InetSocketAddress) myAddress);
+ }
+ session.addPasswordIdentity("user2");
+ session.auth().verify(AUTH_TIMEOUT);
+ assertTrue(session.isAuthenticated());
+ testCommand(session, "ls -al");
+ }
+ }
+ }
+ }
+ }
+
+ private void testCommand(ClientSession session, String command) throws IOException {
+ String result;
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ ByteArrayOutputStream errors = new ByteArrayOutputStream();
+ session.executeRemoteCommand(command, out, errors, StandardCharsets.UTF_8);
+ result = out.toString();
+ assertEquals(command, result);
+ }
+
+}
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/forward/Sshd1033Test.java b/sshd-core/src/test/java/org/apache/sshd/common/forward/Sshd1033Test.java
index 29588d173..c35d2806c 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/forward/Sshd1033Test.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/forward/Sshd1033Test.java
@@ -114,11 +114,11 @@ class Sshd1033Test extends BaseTestSupport {
if (testLocal) {
LOGGER.info("================== Local ==================");
try (ExplicitPortForwardingTracker localTracker = session.createLocalPortForwardingTracker(
- new SshdSocketAddress("localhost", 8082),
+ new SshdSocketAddress("localhost", 0),
new SshdSocketAddress("test.javastack.org", 80))) {
- LOGGER.info("LocalPortForwarding: {} -> {}", localTracker.getLocalAddress(),
+ SshdSocketAddress localSocketAddress = localTracker.getBoundAddress();
+ LOGGER.info("LocalPortForwarding: {} -> {}", localSocketAddress,
localTracker.getRemoteAddress());
- SshdSocketAddress localSocketAddress = localTracker.getLocalAddress();
assertNotNull(localSocketAddress);
Proxy proxy = new Proxy(
Proxy.Type.HTTP,
@@ -130,9 +130,9 @@ class Sshd1033Test extends BaseTestSupport {
if (testDynamic) {
LOGGER.info("================== Dynamic ==================");
try (DynamicPortForwardingTracker dynamicTracker = session.createDynamicPortForwardingTracker(
- new SshdSocketAddress("localhost", 8000))) {
- LOGGER.info("DynamicPortForwarding: {}", dynamicTracker.getLocalAddress());
- SshdSocketAddress dynamicSocketAddress = dynamicTracker.getLocalAddress();
+ new SshdSocketAddress("localhost", 0))) {
+ SshdSocketAddress dynamicSocketAddress = dynamicTracker.getBoundAddress();
+ LOGGER.info("DynamicPortForwarding: {}", dynamicSocketAddress);
assertNotNull(dynamicSocketAddress);
Proxy proxy = new Proxy(
Proxy.Type.SOCKS,
diff --git a/sshd-core/src/test/resources/org/apache/sshd/client/tinyproxy-auth.conf b/sshd-core/src/test/resources/org/apache/sshd/client/tinyproxy-auth.conf
new file mode 100644
index 000000000..27ef2a371
--- /dev/null
+++ b/sshd-core/src/test/resources/org/apache/sshd/client/tinyproxy-auth.conf
@@ -0,0 +1,2 @@
+Port 1080
+BasicAuth httptester testhttp
diff --git a/sshd-core/src/test/resources/org/apache/sshd/client/tinyproxy.conf b/sshd-core/src/test/resources/org/apache/sshd/client/tinyproxy.conf
new file mode 100644
index 000000000..7bbb3d6cf
--- /dev/null
+++ b/sshd-core/src/test/resources/org/apache/sshd/client/tinyproxy.conf
@@ -0,0 +1,2 @@
+Port 1080
+
diff --git a/sshd-mina/pom.xml b/sshd-mina/pom.xml
index 758e31c4d..a110e66dd 100644
--- a/sshd-mina/pom.xml
+++ b/sshd-mina/pom.xml
@@ -128,6 +128,7 @@
<exclude>**/OpenSshMlKemTest.java</exclude>
<exclude>**/PortForwardingWithOpenSshTest.java</exclude>
<exclude>**/StrictKexInteroperabilityTest.java</exclude>
+ <exclude>**/*IntegrationTest.java</exclude>
<!-- reading files from classpath doesn't work correctly w/ reusable test jar -->
<exclude>**/OpenSSHCertificateTest.java</exclude>
<!-- A MinaServiceFactory cannot be instantiated with a mock CloseableExecutorService. -->
@@ -188,6 +189,7 @@
<exclude>**/OpenSshMlKemTest.java</exclude>
<exclude>**/PortForwardingWithOpenSshTest.java</exclude>
<exclude>**/StrictKexInteroperabilityTest.java</exclude>
+ <exclude>**/*IntegrationTest.java</exclude>
<!-- reading files from classpath doesn't work correctly w/ reusable test jar -->
<exclude>**/OpenSSHCertificateTest.java</exclude>
<!-- A MinaServiceFactory cannot be instantiated with a mock CloseableExecutorService. -->
diff --git a/sshd-netty/pom.xml b/sshd-netty/pom.xml
index 8176936ff..4b36d8070 100644
--- a/sshd-netty/pom.xml
+++ b/sshd-netty/pom.xml
@@ -152,6 +152,7 @@
<exclude>**/OpenSshMlKemTest.java</exclude>
<exclude>**/PortForwardingWithOpenSshTest.java</exclude>
<exclude>**/StrictKexInteroperabilityTest.java</exclude>
+ <exclude>**/*IntegrationTest.java</exclude>
<!-- reading files from classpath doesn't work correctly w/ reusable test jar -->
<exclude>**/OpenSSHCertificateTest.java</exclude>
</excludes>