This is an automated email from the ASF dual-hosted git repository. lgoldstein pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/mina-sshd.git
commit 8f12fae2de8110320efcfee12072c77891a2ce78 Author: Lyor Goldstein <[email protected]> AuthorDate: Mon Jun 17 08:01:57 2019 +0300 [SSHD-923] Added mechanism to detect client closing in AgentClient#request --- CHANGES.md | 5 + .../sshd/agent/common/AbstractAgentProxy.java | 12 +-- .../org/apache/sshd/agent/unix/AgentClient.java | 115 ++++++++++++++++----- .../apache/sshd/agent/unix/UnixAgentFactory.java | 2 +- .../test/java/org/apache/sshd/agent/AgentTest.java | 9 +- 5 files changed, 110 insertions(+), 33 deletions(-) diff --git a/CHANGES.md b/CHANGES.md index 5eab448..f27c9bb 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -46,6 +46,9 @@ which they are being invoked. * The various implementations of public/private keys/pairs decoders/loaders are provided with a `Map` of any headers that may be available in the relevant data file. +* `org.apache.sshd.agent.unix.AgentClient` constructor expects a non-*null* `FactoryManager` instance which +it then exposes via its `getFactoryManager`. + ## Minor code helpers * The `Session` object provides a `isServerSession` method that can be used to distinguish between @@ -140,3 +143,5 @@ and therefore closing all currently tracked file/directory handles. * [SSHD-917](https://issues.apache.org/jira/browse/SSHD-917) - Add support for SSH2 public key file format. * [SSHD-921](https://issues.apache.org/jira/browse/SSHD-921) - Do not send session disconnect message due to timeout expiration if already done so. + +* [SSHD-923](https://issues.apache.org/jira/browse/SSHD-923) - Added agent close detection mechanisms to avoid infinite waits on incoming messages. diff --git a/sshd-core/src/main/java/org/apache/sshd/agent/common/AbstractAgentProxy.java b/sshd-core/src/main/java/org/apache/sshd/agent/common/AbstractAgentProxy.java index 27c2112..574e8b2 100644 --- a/sshd-core/src/main/java/org/apache/sshd/agent/common/AbstractAgentProxy.java +++ b/sshd-core/src/main/java/org/apache/sshd/agent/common/AbstractAgentProxy.java @@ -49,7 +49,6 @@ public abstract class AbstractAgentProxy extends AbstractLoggingBean implements private String channelType = FactoryManager.AGENT_FORWARDING_TYPE_OPENSSH; protected AbstractAgentProxy(CloseableExecutorService executorService) { - super(); executor = executorService; } @@ -126,20 +125,19 @@ public abstract class AbstractAgentProxy extends AbstractLoggingBean implements } byte[] signature = buffer.getBytes(); + boolean debugEnabled = log.isDebugEnabled(); if (FactoryManager.AGENT_FORWARDING_TYPE_IETF.equals(channelType)) { - if (log.isDebugEnabled()) { + if (debugEnabled) { log.debug("sign({})[{}] : {}", - KeyUtils.getKeyType(key), KeyUtils.getFingerPrint(key), - BufferUtils.toHex(':', signature)); + KeyUtils.getKeyType(key), KeyUtils.getFingerPrint(key), BufferUtils.toHex(':', signature)); } } else { Buffer buf = new ByteArrayBuffer(signature); String algorithm = buf.getString(); signature = buf.getBytes(); - if (log.isDebugEnabled()) { + if (debugEnabled) { log.debug("sign({})[{}] {}: {}", - KeyUtils.getKeyType(key), KeyUtils.getFingerPrint(key), - algorithm, BufferUtils.toHex(':', signature)); + KeyUtils.getKeyType(key), KeyUtils.getFingerPrint(key), algorithm, BufferUtils.toHex(':', signature)); } } diff --git a/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentClient.java b/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentClient.java index c6d3585..ff6b7e8 100644 --- a/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentClient.java +++ b/sshd-core/src/main/java/org/apache/sshd/agent/unix/AgentClient.java @@ -21,12 +21,17 @@ package org.apache.sshd.agent.unix; import java.io.IOException; import java.io.InterruptedIOException; import java.io.StreamCorruptedException; +import java.util.Objects; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Future; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.sshd.agent.common.AbstractAgentProxy; +import org.apache.sshd.common.FactoryManager; +import org.apache.sshd.common.FactoryManagerHolder; +import org.apache.sshd.common.PropertyResolverUtils; import org.apache.sshd.common.SshException; import org.apache.sshd.common.util.buffer.Buffer; import org.apache.sshd.common.util.buffer.ByteArrayBuffer; @@ -40,9 +45,19 @@ import org.apache.tomcat.jni.Status; /** * A client for a remote SSH agent */ -public class AgentClient extends AbstractAgentProxy implements Runnable { +public class AgentClient extends AbstractAgentProxy implements Runnable, FactoryManagerHolder { + /** + * Time to wait for new incoming messages before checking if the client is still active + */ + public static final String MESSAGE_POLL_FREQUENCY = "agent-client-message-poll-time"; + + /** + * Default value for {@value #MESSAGE_POLL_FREQUENCY} + */ + public static final long DEFAULT_MESSAGE_POLL_FREQUENCY = TimeUnit.MINUTES.toMillis(2L); private final String authSocket; + private final FactoryManager manager; private final long pool; private final long handle; private final Buffer receiveBuffer; @@ -50,16 +65,18 @@ public class AgentClient extends AbstractAgentProxy implements Runnable { private Future<?> pumper; private final AtomicBoolean open = new AtomicBoolean(true); - public AgentClient(String authSocket) throws IOException { - this(authSocket, null); + public AgentClient(FactoryManager manager, String authSocket) throws IOException { + this(manager, authSocket, null); } - public AgentClient(String authSocket, CloseableExecutorService executor) throws IOException { + public AgentClient(FactoryManager manager, String authSocket, CloseableExecutorService executor) throws IOException { super((executor == null) ? ThreadUtils.newSingleThreadExecutor("AgentClient[" + authSocket + "]") : executor); + this.manager = Objects.requireNonNull(manager, "No factory manager instance provided"); this.authSocket = authSocket; try { - pool = Pool.create(AprLibrary.getInstance().getRootPool()); + AprLibrary aprLibInstance = AprLibrary.getInstance(); + pool = Pool.create(aprLibInstance.getRootPool()); handle = Local.create(authSocket, pool); int result = Local.connect(handle, 0); if (result != Status.APR_SUCCESS) { @@ -78,6 +95,15 @@ public class AgentClient extends AbstractAgentProxy implements Runnable { } @Override + public FactoryManager getFactoryManager() { + return manager; + } + + public String getAuthSocket() { + return authSocket; + } + + @Override public boolean isOpen() { return open.get(); } @@ -91,14 +117,20 @@ public class AgentClient extends AbstractAgentProxy implements Runnable { if (result < Status.APR_SUCCESS) { throwException(result); } + messageReceived(new ByteArrayBuffer(buf, 0, result)); } } catch (Exception e) { + boolean debugEnabled = log.isDebugEnabled(); if (isOpen()) { - log.warn(e.getClass().getSimpleName() + " while still open: " + e.getMessage()); + log.warn("run({}) {} while still open: {}", + this, e.getClass().getSimpleName(), e.getMessage()); + if (debugEnabled) { + log.debug("run(" + this + ") open client exception", e); + } } else { - if (log.isDebugEnabled()) { - log.debug("Closed client loop exception", e); + if (debugEnabled) { + log.debug("run(" + this + ") closed client loop exception", e); } } } finally { @@ -106,7 +138,8 @@ public class AgentClient extends AbstractAgentProxy implements Runnable { close(); } catch (IOException e) { if (log.isDebugEnabled()) { - log.debug(e.getClass().getSimpleName() + " while closing: " + e.getMessage()); + log.debug("run({}) {} while closing: {}", + this, e.getClass().getSimpleName(), e.getMessage()); } } } @@ -116,20 +149,22 @@ public class AgentClient extends AbstractAgentProxy implements Runnable { Buffer message = null; synchronized (receiveBuffer) { receiveBuffer.putBuffer(buffer); - if (receiveBuffer.available() >= 4) { + if (receiveBuffer.available() >= Integer.BYTES) { int rpos = receiveBuffer.rpos(); int len = receiveBuffer.getInt(); // Protect against malicious or corrupted packets if (len < 0) { throw new StreamCorruptedException("Illogical message length: " + len); } + receiveBuffer.rpos(rpos); - if (receiveBuffer.available() >= (4 + len)) { + if (receiveBuffer.available() >= (Integer.BYTES + len)) { message = new ByteArrayBuffer(receiveBuffer.getBytes()); receiveBuffer.compact(); } } } + if (message != null) { synchronized (messages) { messages.offer(message); @@ -144,6 +179,11 @@ public class AgentClient extends AbstractAgentProxy implements Runnable { Socket.close(handle); } + // make any waiting thread aware of the closure + synchronized (messages) { + messages.notifyAll(); + } + if ((pumper != null) && (!pumper.isDone())) { pumper.cancel(true); } @@ -158,17 +198,42 @@ public class AgentClient extends AbstractAgentProxy implements Runnable { buffer.putInt(wpos - 4); buffer.wpos(wpos); synchronized (messages) { - try { - int result = Socket.send(handle, buffer.array(), buffer.rpos(), buffer.available()); - if (result < Status.APR_SUCCESS) { - throwException(result); - } - if (messages.isEmpty()) { - messages.wait(); - } + int result = Socket.send(handle, buffer.array(), buffer.rpos(), buffer.available()); + if (result < Status.APR_SUCCESS) { + throwException(result); + } + + return waitForMessageBuffer(); + } + } + + // NOTE: assumes messages lock is obtained prior to calling this method + protected Buffer waitForMessageBuffer() throws IOException { + FactoryManager mgr = getFactoryManager(); + long idleTimeout = PropertyResolverUtils.getLongProperty( + mgr, MESSAGE_POLL_FREQUENCY, DEFAULT_MESSAGE_POLL_FREQUENCY); + if (idleTimeout <= 0L) { + idleTimeout = DEFAULT_MESSAGE_POLL_FREQUENCY; + } + + boolean traceEnabled = log.isTraceEnabled(); + for (int count = 1;; count++) { + if (!isOpen()) { + throw new SshException("Client is being closed"); + } + + if (!messages.isEmpty()) { return messages.poll(); + } + + if (traceEnabled) { + log.trace("waitForMessageBuffer({}) wait iteration #{}", this, count); + } + + try { + messages.wait(idleTimeout); } catch (InterruptedException e) { - throw (IOException) new InterruptedIOException(authSocket + ": Interrupted while polling for messages").initCause(e); + throw (IOException) new InterruptedIOException("Interrupted while waiting for messages at iteration #" + count).initCause(e); } } } @@ -179,10 +244,12 @@ public class AgentClient extends AbstractAgentProxy implements Runnable { * @param code APR error code * @throws java.io.IOException the produced exception for the given APR error number */ - private void throwException(int code) throws IOException { - throw new IOException( - org.apache.tomcat.jni.Error.strerror(-code) - + " (code: " + code + ")"); + protected void throwException(int code) throws IOException { + throw new IOException(org.apache.tomcat.jni.Error.strerror(-code) + " (code: " + code + ")"); } + @Override + public String toString() { + return getClass().getSimpleName() + "[socket=" + getAuthSocket() + "]"; + } } diff --git a/sshd-core/src/main/java/org/apache/sshd/agent/unix/UnixAgentFactory.java b/sshd-core/src/main/java/org/apache/sshd/agent/unix/UnixAgentFactory.java index 9c3b32d..b30bbb3 100644 --- a/sshd-core/src/main/java/org/apache/sshd/agent/unix/UnixAgentFactory.java +++ b/sshd-core/src/main/java/org/apache/sshd/agent/unix/UnixAgentFactory.java @@ -82,7 +82,7 @@ public class UnixAgentFactory implements SshAgentFactory { throw new SshException("No " + SshAgent.SSH_AUTHSOCKET_ENV_NAME + " value"); } - return new AgentClient(authSocket, newExecutor()); + return new AgentClient(manager, authSocket, newExecutor()); } @Override diff --git a/sshd-core/src/test/java/org/apache/sshd/agent/AgentTest.java b/sshd-core/src/test/java/org/apache/sshd/agent/AgentTest.java index 5bb7fa9..ba3b2e1 100644 --- a/sshd-core/src/test/java/org/apache/sshd/agent/AgentTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/agent/AgentTest.java @@ -25,6 +25,7 @@ import java.nio.charset.StandardCharsets; import java.security.KeyPair; import java.security.PublicKey; import java.util.Collection; +import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; @@ -36,6 +37,7 @@ import org.apache.sshd.agent.unix.AprLibrary; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.channel.ChannelShell; import org.apache.sshd.client.session.ClientSession; +import org.apache.sshd.common.FactoryManager; import org.apache.sshd.common.keyprovider.FileKeyPairProvider; import org.apache.sshd.common.keyprovider.KeyPairProvider; import org.apache.sshd.common.util.security.SecurityUtils; @@ -53,6 +55,7 @@ import org.junit.BeforeClass; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; +import org.mockito.Mockito; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class AgentTest extends BaseTestSupport { @@ -83,7 +86,11 @@ public class AgentTest extends BaseTestSupport { try (AgentServer agent = new AgentServer()) { String authSocket = agent.start(); - try (SshAgent client = new AgentClient(authSocket)) { + FactoryManager manager = Mockito.mock(FactoryManager.class); + Mockito.when(manager.getParentPropertyResolver()).thenReturn(null); + Mockito.when(manager.getProperties()).thenReturn(Collections.emptyMap()); + + try (SshAgent client = new AgentClient(manager, authSocket)) { Iterable<? extends Map.Entry<PublicKey, String>> keys = client.getIdentities(); assertNotNull("No initial identities", keys); assertObjectInstanceOf("Non collection initial identities", Collection.class, keys);
