You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by lg...@apache.org on 2019/10/20 15:30:24 UTC

[mina-sshd] branch master updated (77859da -> 32f9eb6)

This is an automated email from the ASF dual-hosted git repository.

lgoldstein pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git.


    from 77859da  [SSHD-914] Added Python 3 script based on Paramiko package to interact with MINA SSHD as an SFTP client
     new 1a98fbc  [SSHD-914] Make sure Ptyhon script CWD prompt is shown on time for the user to see it
     new 88f81a4  [SSHD-949] Session should use cipher block size and not IV size to calculate padding
     new b19dafd  [SSHD-842] Moved some IoXXX interface definitions from core to common module
     new a31a83a  [SSHD-842] Moved UserAuthMethodFactory from core to common module
     new 15b74e9  [SSHD-842] Moved KexProposalOptionTest from core to common module
     new b8fadd4  [SSHD-842] Updated client ConnectFuture and other ClientSessionHolder(s) hierarchy
     new 32f9eb6  [SSHD-842] Updated hierarchy of ServerSessionHolder(s)

The 7 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.


Summary of changes:
 CHANGES.md                                         |   4 +-
 .../sshd/common/auth/UserAuthMethodFactory.java    |   0
 .../sshd/common/io/AbstractIoWriteFuture.java      |   0
 .../java/org/apache/sshd/common/io/IoAcceptor.java |   0
 .../org/apache/sshd/common/io/IoConnectFuture.java |   0
 .../org/apache/sshd/common/io/IoConnector.java     |   3 +-
 .../java/org/apache/sshd/common/io/IoHandler.java  |   1 -
 .../apache/sshd/common/io/IoHandlerFactory.java    |   0
 .../org/apache/sshd/common/io/IoInputStream.java   |   2 -
 .../org/apache/sshd/common/io/IoOutputStream.java  |   0
 .../org/apache/sshd/common/io/IoReadFuture.java    |   0
 .../java/org/apache/sshd/common/io/IoService.java  |   0
 .../sshd/common/io/IoServiceEventListener.java     |   0
 .../common/io/IoServiceEventListenerManager.java   |   0
 .../apache/sshd/common/io/IoServiceFactory.java    |   0
 .../java/org/apache/sshd/common/io/IoSession.java  |   0
 .../org/apache/sshd/common/io/IoWriteFuture.java   |   0
 .../org/apache/sshd/common/io/PacketWriter.java    |  25 +++
 .../sshd/common/io/ReadPendingException.java       |   0
 .../sshd/common/io/WritePendingException.java      |   0
 .../apache/sshd/common/cipher/AES192CTRTest.java   |   2 +-
 .../apache/sshd/common/cipher/AES256CBCTest.java   |   2 +-
 .../apache/sshd/common/cipher/ARCFOUR256Test.java  |   2 +-
 .../apache/sshd/common/cipher/BaseCipherTest.java  |  40 +++--
 .../sshd/common/kex/KexProposalOptionTest.java     |  17 +-
 .../InteractivePasswordIdentityProvider.java       |  12 +-
 .../java/org/apache/sshd/client/auth/UserAuth.java |   2 -
 .../sshd/client/channel/AbstractClientChannel.java |   7 -
 .../apache/sshd/client/channel/ClientChannel.java  |   6 +
 .../apache/sshd/client/future/ConnectFuture.java   |  17 +-
 .../client/kex/AbstractDHClientKeyExchange.java    |   7 +-
 .../client/session/ClientConnectionService.java    |   8 +-
 .../sshd/client/session/ClientUserAuthService.java |  21 +--
 .../forward/DynamicPortForwardingTracker.java      |   3 +-
 .../session/forward/PortForwardingTracker.java     |  12 +-
 .../client/subsystem/AbstractSubsystemClient.java  |   6 -
 .../sshd/client/subsystem/SubsystemClient.java     |   5 +-
 .../main/java/org/apache/sshd/common/Service.java  |   5 +-
 .../org/apache/sshd/common/channel/Channel.java    |   9 +-
 .../common/session/helpers/AbstractSession.java    | 179 +++++++++++++--------
 .../sshd/common/session/helpers/SessionHelper.java |   6 +-
 .../java/org/apache/sshd/server/auth/UserAuth.java |   1 -
 .../sshd/server/channel/AbstractServerChannel.java |   7 -
 .../apache/sshd/server/channel/ServerChannel.java  |   6 +-
 .../server/command/AbstractCommandSupport.java     |  31 ++--
 .../server/kex/AbstractDHServerKeyExchange.java    |  12 +-
 .../apache/sshd/server/shell/InvertedShell.java    |  15 +-
 .../org/apache/sshd/server/shell/ProcessShell.java |  23 +--
 .../sshd/common/cipher/BuiltinCiphersTest.java     |   3 +-
 .../org/apache/sshd/common/cipher/CipherTest.java  |  24 ++-
 .../server/shell/InvertedShellWrapperTest.java     |  28 +++-
 .../apache/sshd/util/test/BogusInvertedShell.java  |   4 +-
 .../sshd/git/transport/GitSshdSessionFactory.java  |  14 +-
 .../apache/sshd/client/scp/AbstractScpClient.java  |   5 -
 .../java/org/apache/sshd/client/scp/ScpClient.java |   5 +
 .../client/subsystem/sftp/fs/SftpFileSystem.java   |  10 +-
 .../subsystem/sftp/SftpSubsystemEnvironment.java   |   9 +-
 sshd-sources/python/sftpclient.py                  |   3 +-
 58 files changed, 407 insertions(+), 196 deletions(-)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/auth/UserAuthMethodFactory.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoAcceptor.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoConnectFuture.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoConnector.java (92%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoHandler.java (99%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoHandlerFactory.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoInputStream.java (99%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoOutputStream.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoReadFuture.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoService.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoServiceEventListener.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoServiceEventListenerManager.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoServiceFactory.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoSession.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/IoWriteFuture.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/PacketWriter.java (65%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/ReadPendingException.java (100%)
 rename {sshd-core => sshd-common}/src/main/java/org/apache/sshd/common/io/WritePendingException.java (100%)
 rename {sshd-core => sshd-common}/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java (90%)


[mina-sshd] 06/07: [SSHD-842] Updated client ConnectFuture and other ClientSessionHolder(s) hierarchy

Posted by lg...@apache.org.
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 b8fadd4ff18bcf20b25387591b66b6b39210d341
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Oct 17 13:18:58 2019 +0300

    [SSHD-842] Updated client ConnectFuture and other ClientSessionHolder(s) hierarchy
---
 .../password/InteractivePasswordIdentityProvider.java   | 12 ++++++++++--
 .../main/java/org/apache/sshd/client/auth/UserAuth.java |  2 --
 .../sshd/client/channel/AbstractClientChannel.java      |  7 -------
 .../org/apache/sshd/client/channel/ClientChannel.java   |  6 ++++++
 .../org/apache/sshd/client/future/ConnectFuture.java    | 17 ++++++++++++-----
 .../sshd/client/kex/AbstractDHClientKeyExchange.java    |  7 +++++--
 .../sshd/client/session/ClientConnectionService.java    |  8 ++++----
 .../session/forward/DynamicPortForwardingTracker.java   |  3 ++-
 .../client/session/forward/PortForwardingTracker.java   | 12 ++++++++++--
 .../sshd/client/subsystem/AbstractSubsystemClient.java  |  6 ------
 .../apache/sshd/client/subsystem/SubsystemClient.java   |  5 ++++-
 .../java/org/apache/sshd/common/channel/Channel.java    |  9 +++------
 .../sshd/git/transport/GitSshdSessionFactory.java       | 14 ++++++++++++--
 .../org/apache/sshd/client/scp/AbstractScpClient.java   |  5 -----
 .../main/java/org/apache/sshd/client/scp/ScpClient.java |  5 +++++
 .../sshd/client/subsystem/sftp/fs/SftpFileSystem.java   | 10 +++++++++-
 16 files changed, 82 insertions(+), 46 deletions(-)

diff --git a/sshd-contrib/src/main/java/org/apache/sshd/client/auth/password/InteractivePasswordIdentityProvider.java b/sshd-contrib/src/main/java/org/apache/sshd/client/auth/password/InteractivePasswordIdentityProvider.java
index 4c47058..4106d9d 100644
--- a/sshd-contrib/src/main/java/org/apache/sshd/client/auth/password/InteractivePasswordIdentityProvider.java
+++ b/sshd-contrib/src/main/java/org/apache/sshd/client/auth/password/InteractivePasswordIdentityProvider.java
@@ -26,6 +26,7 @@ import java.util.concurrent.atomic.AtomicReference;
 import org.apache.sshd.client.auth.keyboard.UserInteraction;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.client.session.ClientSessionHolder;
+import org.apache.sshd.common.session.SessionHolder;
 import org.apache.sshd.common.util.GenericUtils;
 
 /**
@@ -60,7 +61,8 @@ import org.apache.sshd.common.util.GenericUtils;
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public class InteractivePasswordIdentityProvider implements Iterator<String>, ClientSessionHolder {
+public class InteractivePasswordIdentityProvider
+        implements Iterator<String>, SessionHolder<ClientSession>, ClientSessionHolder {
     /** Special marker to indicate that we exhausted all attempts */
     protected static final String EOF = "EOF";
 
@@ -69,7 +71,8 @@ public class InteractivePasswordIdentityProvider implements Iterator<String>, Cl
     private String prompt;
     private AtomicReference<String> nextPassword = new AtomicReference<>();
 
-    public InteractivePasswordIdentityProvider(ClientSession clientSession, UserInteraction userInteraction, String prompt) {
+    public InteractivePasswordIdentityProvider(
+            ClientSession clientSession, UserInteraction userInteraction, String prompt) {
         this.clientSession = Objects.requireNonNull(clientSession, "No client session provided");
         this.userInteraction = Objects.requireNonNull(userInteraction, "No user interaction instance configured");
         this.prompt = prompt;
@@ -80,6 +83,11 @@ public class InteractivePasswordIdentityProvider implements Iterator<String>, Cl
         return clientSession;
     }
 
+    @Override
+    public ClientSession getSession() {
+        return getClientSession();
+    }
+
     public UserInteraction getUserInteraction() {
         return userInteraction;
     }
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/auth/UserAuth.java b/sshd-core/src/main/java/org/apache/sshd/client/auth/UserAuth.java
index 633e761..03792f4 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/auth/UserAuth.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/auth/UserAuth.java
@@ -28,7 +28,6 @@ import org.apache.sshd.common.util.buffer.Buffer;
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public interface UserAuth extends ClientSessionHolder, UserAuthInstance<ClientSession> {
-
     /**
      * @param session The {@link ClientSession}
      * @param service The requesting service name
@@ -50,5 +49,4 @@ public interface UserAuth extends ClientSessionHolder, UserAuthInstance<ClientSe
      * Called to release any allocated resources
      */
     void destroy();
-
 }
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
index 611e789..93832c6 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/AbstractClientChannel.java
@@ -34,7 +34,6 @@ import org.apache.sshd.client.channel.exit.ExitSignalChannelRequestHandler;
 import org.apache.sshd.client.channel.exit.ExitStatusChannelRequestHandler;
 import org.apache.sshd.client.future.DefaultOpenFuture;
 import org.apache.sshd.client.future.OpenFuture;
-import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.FactoryManager;
 import org.apache.sshd.common.SshConstants;
@@ -62,7 +61,6 @@ import org.apache.sshd.common.util.io.IoUtils;
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public abstract class AbstractClientChannel extends AbstractChannel implements ClientChannel {
-
     protected final AtomicBoolean opened = new AtomicBoolean();
 
     protected Streaming streaming;
@@ -103,11 +101,6 @@ public abstract class AbstractClientChannel extends AbstractChannel implements C
         });
     }
 
-    @Override
-    public ClientSession getClientSession() {
-        return (ClientSession) super.getSession();
-    }
-
     protected void addChannelSignalRequestHandlers(EventNotifier<String> notifier) {
         addRequestHandler(new ExitStatusChannelRequestHandler(exitStatusHolder, notifier));
         addRequestHandler(new ExitSignalChannelRequestHandler(exitSignalHolder, notifier));
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannel.java b/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannel.java
index c5a87c4..73f046b 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/channel/ClientChannel.java
@@ -27,6 +27,7 @@ import java.util.Collection;
 import java.util.Set;
 
 import org.apache.sshd.client.future.OpenFuture;
+import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.client.session.ClientSessionHolder;
 import org.apache.sshd.common.channel.Channel;
 import org.apache.sshd.common.io.IoInputStream;
@@ -46,6 +47,11 @@ public interface ClientChannel extends Channel, ClientSessionHolder {
         Sync
     }
 
+    @Override
+    default ClientSession getClientSession() {
+        return (ClientSession) getSession();
+    }
+
     /**
      * @return The type of channel reported when it was created
      */
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/future/ConnectFuture.java b/sshd-core/src/main/java/org/apache/sshd/client/future/ConnectFuture.java
index 47d4fa9..5db35d4 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/future/ConnectFuture.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/future/ConnectFuture.java
@@ -19,19 +19,26 @@
 package org.apache.sshd.client.future;
 
 import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.client.session.ClientSessionHolder;
 import org.apache.sshd.common.future.SshFuture;
 import org.apache.sshd.common.future.VerifiableFuture;
+import org.apache.sshd.common.session.SessionHolder;
 
 /**
  * An {@link SshFuture} for asynchronous connections requests.
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public interface ConnectFuture extends SshFuture<ConnectFuture>, VerifiableFuture<ConnectFuture> {
-    /**
-     * @return The referenced {@link ClientSession}
-     */
-    ClientSession getSession();
+public interface ConnectFuture
+        extends SshFuture<ConnectFuture>,
+        VerifiableFuture<ConnectFuture>,
+        SessionHolder<ClientSession>,
+        ClientSessionHolder {
+
+    @Override
+    default ClientSession getClientSession() {
+        return getSession();
+    }
 
     /**
      * @return <code>true</code> if the connect operation is finished successfully.
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/kex/AbstractDHClientKeyExchange.java b/sshd-core/src/main/java/org/apache/sshd/client/kex/AbstractDHClientKeyExchange.java
index 3158a2a..3bbf1e9 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/kex/AbstractDHClientKeyExchange.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/kex/AbstractDHClientKeyExchange.java
@@ -30,11 +30,14 @@ import org.apache.sshd.common.util.ValidateUtils;
 /**
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public abstract class AbstractDHClientKeyExchange extends AbstractDHKeyExchange implements ClientSessionHolder {
+public abstract class AbstractDHClientKeyExchange
+            extends AbstractDHKeyExchange
+            implements ClientSessionHolder {
     protected PublicKey serverKey;
 
     protected AbstractDHClientKeyExchange(Session session) {
-        super(ValidateUtils.checkInstanceOf(session, ClientSession.class, "Using a client side KeyExchange on a server: %s", session));
+        super(ValidateUtils.checkInstanceOf(session, ClientSession.class,
+            "Using a client side KeyExchange on a server: %s", session));
     }
 
     @Override
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientConnectionService.java b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientConnectionService.java
index dd472bd..8911cc5 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientConnectionService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientConnectionService.java
@@ -52,11 +52,11 @@ public class ClientConnectionService
     public ClientConnectionService(AbstractClientSession s) throws SshException {
         super(s);
 
-        heartbeatRequest = this.getStringProperty(
+        heartbeatRequest = getStringProperty(
             ClientFactoryManager.HEARTBEAT_REQUEST, ClientFactoryManager.DEFAULT_KEEP_ALIVE_HEARTBEAT_STRING);
-        heartbeatInterval = this.getLongProperty(
+        heartbeatInterval = getLongProperty(
             ClientFactoryManager.HEARTBEAT_INTERVAL, ClientFactoryManager.DEFAULT_HEARTBEAT_INTERVAL);
-        heartbeatReplyMaxWait = this.getLongProperty(
+        heartbeatReplyMaxWait = getLongProperty(
             ClientFactoryManager.HEARTBEAT_REPLY_WAIT, ClientFactoryManager.DEFAULT_HEARTBEAT_REPLY_WAIT);
     }
 
@@ -65,7 +65,7 @@ public class ClientConnectionService
         return getSession();
     }
 
-    @Override
+    @Override   // co-variant return
     public AbstractClientSession getSession() {
         return (AbstractClientSession) super.getSession();
     }
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/forward/DynamicPortForwardingTracker.java b/sshd-core/src/main/java/org/apache/sshd/client/session/forward/DynamicPortForwardingTracker.java
index cb1a977..8755aed 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/forward/DynamicPortForwardingTracker.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/forward/DynamicPortForwardingTracker.java
@@ -29,7 +29,8 @@ import org.apache.sshd.common.util.net.SshdSocketAddress;
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public class DynamicPortForwardingTracker extends PortForwardingTracker {
-    public DynamicPortForwardingTracker(ClientSession session, SshdSocketAddress localAddress, SshdSocketAddress boundAddress) {
+    public DynamicPortForwardingTracker(
+            ClientSession session, SshdSocketAddress localAddress, SshdSocketAddress boundAddress) {
         super(session, localAddress, boundAddress);
     }
 
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/forward/PortForwardingTracker.java b/sshd-core/src/main/java/org/apache/sshd/client/session/forward/PortForwardingTracker.java
index ab6d12a..b1e3785 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/forward/PortForwardingTracker.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/forward/PortForwardingTracker.java
@@ -25,18 +25,21 @@ import java.util.concurrent.atomic.AtomicBoolean;
 
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.client.session.ClientSessionHolder;
+import org.apache.sshd.common.session.SessionHolder;
 import org.apache.sshd.common.util.net.SshdSocketAddress;
 
 /**
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public abstract class PortForwardingTracker implements Channel, ClientSessionHolder {
+public abstract class PortForwardingTracker
+        implements Channel, SessionHolder<ClientSession>, ClientSessionHolder {
     protected final AtomicBoolean open = new AtomicBoolean(true);
     private final ClientSession session;
     private final SshdSocketAddress localAddress;
     private final SshdSocketAddress boundAddress;
 
-    protected PortForwardingTracker(ClientSession session, SshdSocketAddress localAddress, SshdSocketAddress boundAddress) {
+    protected PortForwardingTracker(
+            ClientSession session, SshdSocketAddress localAddress, SshdSocketAddress boundAddress) {
         this.session = Objects.requireNonNull(session, "No client session provided");
         this.localAddress = Objects.requireNonNull(localAddress, "No local address specified");
         this.boundAddress  = Objects.requireNonNull(boundAddress, "No bound address specified");
@@ -61,6 +64,11 @@ public abstract class PortForwardingTracker implements Channel, ClientSessionHol
     }
 
     @Override
+    public ClientSession getSession() {
+        return getClientSession();
+    }
+
+    @Override
     public String toString() {
         return getClass().getSimpleName()
             + "[session=" + getClientSession()
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/AbstractSubsystemClient.java b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/AbstractSubsystemClient.java
index 32e8d26..414f50c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/AbstractSubsystemClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/AbstractSubsystemClient.java
@@ -19,7 +19,6 @@
 
 package org.apache.sshd.client.subsystem;
 
-import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.common.util.logging.AbstractLoggingBean;
 
 /**
@@ -31,11 +30,6 @@ public abstract class AbstractSubsystemClient extends AbstractLoggingBean implem
     }
 
     @Override
-    public final ClientSession getSession() {
-        return getClientSession();
-    }
-
-    @Override
     public String toString() {
         return getClass().getSimpleName()
             + "[name=" + getName()
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/SubsystemClient.java b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/SubsystemClient.java
index 2cf7399..dd6d02d 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/subsystem/SubsystemClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/subsystem/SubsystemClient.java
@@ -36,5 +36,8 @@ public interface SubsystemClient
                 NamedResource,
                 Channel,
                 ClientChannelHolder {
-    // nothing extra
+    @Override
+    default ClientSession getSession() {
+        return getClientSession();
+    }
 }
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/Channel.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/Channel.java
index 4f89ce8..968587d 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/channel/Channel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/Channel.java
@@ -32,6 +32,7 @@ import org.apache.sshd.common.channel.throttle.ChannelStreamPacketWriterResolver
 import org.apache.sshd.common.io.PacketWriter;
 import org.apache.sshd.common.session.ConnectionService;
 import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.session.SessionHolder;
 import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 
@@ -42,7 +43,8 @@ import org.apache.sshd.common.util.buffer.Buffer;
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public interface Channel
-        extends ChannelListenerManager,
+        extends SessionHolder<Session>,
+                ChannelListenerManager,
                 PropertyResolver,
                 AttributeStore,
                 PacketWriter,
@@ -63,11 +65,6 @@ public interface Channel
      */
     int getRecipient();
 
-    /**
-     * @return The channel's underlying {@link Session}
-     */
-    Session getSession();
-
     Window getLocalWindow();
 
     Window getRemoteWindow();
diff --git a/sshd-git/src/main/java/org/apache/sshd/git/transport/GitSshdSessionFactory.java b/sshd-git/src/main/java/org/apache/sshd/git/transport/GitSshdSessionFactory.java
index 75281c5..f619f91 100644
--- a/sshd-git/src/main/java/org/apache/sshd/git/transport/GitSshdSessionFactory.java
+++ b/sshd-git/src/main/java/org/apache/sshd/git/transport/GitSshdSessionFactory.java
@@ -24,6 +24,7 @@ import java.util.Objects;
 import org.apache.sshd.client.SshClient;
 import org.apache.sshd.client.session.ClientSession;
 import org.apache.sshd.client.session.ClientSessionHolder;
+import org.apache.sshd.common.session.SessionHolder;
 import org.apache.sshd.common.util.GenericUtils;
 import org.eclipse.jgit.errors.TransportException;
 import org.eclipse.jgit.transport.CredentialsProvider;
@@ -37,7 +38,9 @@ import org.eclipse.jgit.util.FS;
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public class GitSshdSessionFactory extends SshSessionFactory implements ClientSessionHolder {
+public class GitSshdSessionFactory
+        extends SshSessionFactory
+        implements SessionHolder<ClientSession>, ClientSessionHolder {
     public static final GitSshdSessionFactory INSTANCE = new GitSshdSessionFactory();
 
     private final SshClient client;
@@ -75,7 +78,9 @@ public class GitSshdSessionFactory extends SshSessionFactory implements ClientSe
     }
 
     @Override
-    public RemoteSession getSession(URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms) throws TransportException {
+    public RemoteSession getSession(
+            URIish uri, CredentialsProvider credentialsProvider, FS fs, int tms)
+                throws TransportException {
         try {
             return new GitSshdSession(uri, credentialsProvider, fs, tms) {
                 @Override
@@ -133,4 +138,9 @@ public class GitSshdSessionFactory extends SshSessionFactory implements ClientSe
     public ClientSession getClientSession() {
         return session;
     }
+
+    @Override
+    public ClientSession getSession() {
+        return getClientSession();
+    }
 }
diff --git a/sshd-scp/src/main/java/org/apache/sshd/client/scp/AbstractScpClient.java b/sshd-scp/src/main/java/org/apache/sshd/client/scp/AbstractScpClient.java
index bf8aa22..99bc8e4 100644
--- a/sshd-scp/src/main/java/org/apache/sshd/client/scp/AbstractScpClient.java
+++ b/sshd-scp/src/main/java/org/apache/sshd/client/scp/AbstractScpClient.java
@@ -63,11 +63,6 @@ public abstract class AbstractScpClient extends AbstractLoggingBean implements S
     }
 
     @Override
-    public final ClientSession getSession() {
-        return getClientSession();
-    }
-
-    @Override
     public void download(String[] remote, String local, Collection<Option> options) throws IOException {
         local = ValidateUtils.checkNotNullAndNotEmpty(local, "Invalid argument local: %s", local);
         remote = ValidateUtils.checkNotNullAndNotEmpty(remote, "Invalid argument remote: %s", (Object) remote);
diff --git a/sshd-scp/src/main/java/org/apache/sshd/client/scp/ScpClient.java b/sshd-scp/src/main/java/org/apache/sshd/client/scp/ScpClient.java
index 0e98e0c..a03f77b 100644
--- a/sshd-scp/src/main/java/org/apache/sshd/client/scp/ScpClient.java
+++ b/sshd-scp/src/main/java/org/apache/sshd/client/scp/ScpClient.java
@@ -66,6 +66,11 @@ public interface ScpClient extends SessionHolder<ClientSession>, ClientSessionHo
     String SCP_EXEC_CHANNEL_EXIT_STATUS_TIMEOUT = "scp-exec-channel-exit-status-timeout";
     long DEFAULT_EXEC_CHANNEL_EXIT_STATUS_TIMEOUT = TimeUnit.SECONDS.toMillis(5L);
 
+    @Override
+    default ClientSession getSession() {
+        return getClientSession();
+    }
+
     default void download(String remote, String local, Option... options) throws IOException {
         download(remote, local, GenericUtils.of(options));
     }
diff --git a/sshd-sftp/src/main/java/org/apache/sshd/client/subsystem/sftp/fs/SftpFileSystem.java b/sshd-sftp/src/main/java/org/apache/sshd/client/subsystem/sftp/fs/SftpFileSystem.java
index 1602e9f..dc76927 100644
--- a/sshd-sftp/src/main/java/org/apache/sshd/client/subsystem/sftp/fs/SftpFileSystem.java
+++ b/sshd-sftp/src/main/java/org/apache/sshd/client/subsystem/sftp/fs/SftpFileSystem.java
@@ -49,11 +49,14 @@ import org.apache.sshd.client.subsystem.sftp.SftpClientFactory;
 import org.apache.sshd.client.subsystem.sftp.SftpVersionSelector;
 import org.apache.sshd.client.subsystem.sftp.impl.AbstractSftpClient;
 import org.apache.sshd.common.file.util.BaseFileSystem;
+import org.apache.sshd.common.session.SessionHolder;
 import org.apache.sshd.common.subsystem.sftp.SftpConstants;
 import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 
-public class SftpFileSystem extends BaseFileSystem<SftpPath> implements ClientSessionHolder {
+public class SftpFileSystem
+        extends BaseFileSystem<SftpPath>
+        implements SessionHolder<ClientSession>, ClientSessionHolder {
     public static final String POOL_SIZE_PROP = "sftp-fs-pool-size";
     public static final int DEFAULT_POOL_SIZE = 8;
 
@@ -156,6 +159,11 @@ public class SftpFileSystem extends BaseFileSystem<SftpPath> implements ClientSe
         return clientSession;
     }
 
+    @Override
+    public ClientSession getSession() {
+        return getClientSession();
+    }
+
     @SuppressWarnings("synthetic-access")
     public SftpClient getClient() throws IOException {
         Wrapper wrapper = wrappers.get();


[mina-sshd] 03/07: [SSHD-842] Moved some IoXXX interface definitions from core to common module

Posted by lg...@apache.org.
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 b19dafdca3cc7186c6bb710d2b2e25af2162176e
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Oct 17 11:33:02 2019 +0300

    [SSHD-842] Moved some IoXXX interface definitions from core to common module
---
 .../src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java | 0
 .../src/main/java/org/apache/sshd/common/io/IoAcceptor.java            | 0
 .../src/main/java/org/apache/sshd/common/io/IoConnectFuture.java       | 0
 .../src/main/java/org/apache/sshd/common/io/IoConnector.java           | 3 ++-
 .../src/main/java/org/apache/sshd/common/io/IoHandler.java             | 1 -
 .../src/main/java/org/apache/sshd/common/io/IoHandlerFactory.java      | 0
 .../src/main/java/org/apache/sshd/common/io/IoInputStream.java         | 2 --
 .../src/main/java/org/apache/sshd/common/io/IoOutputStream.java        | 0
 .../src/main/java/org/apache/sshd/common/io/IoReadFuture.java          | 0
 .../src/main/java/org/apache/sshd/common/io/IoService.java             | 0
 .../main/java/org/apache/sshd/common/io/IoServiceEventListener.java    | 0
 .../java/org/apache/sshd/common/io/IoServiceEventListenerManager.java  | 0
 .../src/main/java/org/apache/sshd/common/io/IoServiceFactory.java      | 0
 .../src/main/java/org/apache/sshd/common/io/IoSession.java             | 0
 .../src/main/java/org/apache/sshd/common/io/IoWriteFuture.java         | 0
 .../src/main/java/org/apache/sshd/common/io/PacketWriter.java          | 0
 .../src/main/java/org/apache/sshd/common/io/ReadPendingException.java  | 0
 .../src/main/java/org/apache/sshd/common/io/WritePendingException.java | 0
 18 files changed, 2 insertions(+), 4 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java b/sshd-common/src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/AbstractIoWriteFuture.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoAcceptor.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoAcceptor.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoAcceptor.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoAcceptor.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoConnectFuture.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoConnectFuture.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoConnectFuture.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoConnectFuture.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoConnector.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoConnector.java
similarity index 92%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoConnector.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoConnector.java
index 193a209..e62ea77 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/io/IoConnector.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/io/IoConnector.java
@@ -34,5 +34,6 @@ public interface IoConnector extends IoService {
      * automatic ephemeral port and bind address is used
      * @return The {@link IoConnectFuture future} representing the connection request
      */
-    IoConnectFuture connect(SocketAddress targetAddress, AttributeRepository context, SocketAddress localAddress);
+    IoConnectFuture connect(
+        SocketAddress targetAddress, AttributeRepository context, SocketAddress localAddress);
 }
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoHandler.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoHandler.java
similarity index 99%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoHandler.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoHandler.java
index 81253eb..42abfe5 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/io/IoHandler.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/io/IoHandler.java
@@ -31,5 +31,4 @@ public interface IoHandler {
     void exceptionCaught(IoSession session, Throwable cause) throws Exception;
 
     void messageReceived(IoSession session, Readable message) throws Exception;
-
 }
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoHandlerFactory.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoHandlerFactory.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoHandlerFactory.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoHandlerFactory.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoInputStream.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoInputStream.java
similarity index 99%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoInputStream.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoInputStream.java
index 6bb23a7..fcb5c42 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/io/IoInputStream.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/io/IoInputStream.java
@@ -22,7 +22,6 @@ import org.apache.sshd.common.Closeable;
 import org.apache.sshd.common.util.buffer.Buffer;
 
 public interface IoInputStream extends Closeable {
-
     /**
      * NOTE: the buffer must not be touched until the returned read future is completed.
      *
@@ -30,5 +29,4 @@ public interface IoInputStream extends Closeable {
      * @return The {@link IoReadFuture} for the operation
      */
     IoReadFuture read(Buffer buffer);
-
 }
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoOutputStream.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoOutputStream.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoOutputStream.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoOutputStream.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoReadFuture.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoReadFuture.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoReadFuture.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoReadFuture.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoService.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoService.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoService.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoService.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoServiceEventListener.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoServiceEventListener.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoServiceEventListener.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoServiceEventListener.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoServiceEventListenerManager.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoServiceEventListenerManager.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoServiceEventListenerManager.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoServiceEventListenerManager.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoServiceFactory.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoServiceFactory.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoServiceFactory.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoServiceFactory.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoSession.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoSession.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoSession.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoSession.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/IoWriteFuture.java b/sshd-common/src/main/java/org/apache/sshd/common/io/IoWriteFuture.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/IoWriteFuture.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/IoWriteFuture.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/PacketWriter.java b/sshd-common/src/main/java/org/apache/sshd/common/io/PacketWriter.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/PacketWriter.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/PacketWriter.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/ReadPendingException.java b/sshd-common/src/main/java/org/apache/sshd/common/io/ReadPendingException.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/ReadPendingException.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/ReadPendingException.java
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/WritePendingException.java b/sshd-common/src/main/java/org/apache/sshd/common/io/WritePendingException.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/io/WritePendingException.java
rename to sshd-common/src/main/java/org/apache/sshd/common/io/WritePendingException.java


[mina-sshd] 01/07: [SSHD-914] Make sure Ptyhon script CWD prompt is shown on time for the user to see it

Posted by lg...@apache.org.
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 1a98fbc5173e05307bdb6c65ece99d8f7191e794
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Oct 17 10:25:40 2019 +0300

    [SSHD-914] Make sure Ptyhon script CWD prompt is shown on time for the user to see it
---
 sshd-sources/python/sftpclient.py | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/sshd-sources/python/sftpclient.py b/sshd-sources/python/sftpclient.py
index f8df143..bcd5976 100644
--- a/sshd-sources/python/sftpclient.py
+++ b/sshd-sources/python/sftpclient.py
@@ -336,6 +336,7 @@ def doSftp(sftp):
     while True:
         curdir = sftp.getcwd()
         sys.stdout.write("%s > " % curdir)
+        sys.stdout.flush()
         l = sys.stdin.readline()
         l = l.strip()
     
@@ -403,4 +404,4 @@ if __name__ == "__main__":
         print("Use Ctrl+Break to stop the script")
     else:
         print("Use Ctrl+C to stop the script")
-    main(sys.argv[1:])
\ No newline at end of file
+    main(sys.argv[1:])


[mina-sshd] 02/07: [SSHD-949] Session should use cipher block size and not IV size to calculate padding

Posted by lg...@apache.org.
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 88f81a47ec899657e38d0b90ac77526f0a68bfa7
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Oct 17 10:26:28 2019 +0300

    [SSHD-949] Session should use cipher block size and not IV size to calculate padding
---
 CHANGES.md                                         |   4 +-
 .../apache/sshd/common/cipher/AES192CTRTest.java   |   2 +-
 .../apache/sshd/common/cipher/AES256CBCTest.java   |   2 +-
 .../apache/sshd/common/cipher/ARCFOUR256Test.java  |   2 +-
 .../apache/sshd/common/cipher/BaseCipherTest.java  |  40 +++--
 .../org/apache/sshd/common/io/PacketWriter.java    |  25 +++
 .../common/session/helpers/AbstractSession.java    | 179 +++++++++++++--------
 .../sshd/common/session/helpers/SessionHelper.java |   6 +-
 .../sshd/common/cipher/BuiltinCiphersTest.java     |   3 +-
 .../org/apache/sshd/common/cipher/CipherTest.java  |  24 ++-
 10 files changed, 201 insertions(+), 86 deletions(-)

diff --git a/CHANGES.md b/CHANGES.md
index 6ac150d..9193bbf 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -35,7 +35,7 @@ the standard does not specifically specify the behavior regarding symbolic links
 `createKeyExchange` method that accepts the session instance through which the request is made.
 
 * `Signature` methods accept a `SessionContext` argument representing the session context
-of their invocation (if any)
+of their invocation (if any).
 
 * Default MAC(s) list is set according to the [ssh_config(5)](https://www.freebsd.org/cgi/man.cgi?query=ssh_config&sektion=5)
 order as **first** ones, where the supported MAC(s) that do no appear in it come last.
@@ -93,3 +93,5 @@ for the server's identification before sending KEX-INIT message.
 
 * [SSHD-948](https://issues.apache.org/jira/browse/SSHD-948) - Do not accept password authentication if the session is not encrypted.
 
+* [SSHD-949](https://issues.apache.org/jira/browse/SSHD-949) - Session should use cipher block size and not IV size to calculate padding.
+
diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES192CTRTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES192CTRTest.java
index 6611702..bdd220a 100644
--- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES192CTRTest.java
+++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES192CTRTest.java
@@ -35,7 +35,7 @@ public class AES192CTRTest extends BaseCipherTest {
     @Test
     public void testEncryptDecrypt() throws Exception {
         // for AES 256 bits we need the JCE unlimited strength policy
-        ensureKeySizeSupported(16, 24, "AES", "AES/CTR/NoPadding");
+        ensureFullCipherInformationSupported(BuiltinCiphers.aes192ctr);
         testEncryptDecrypt(BuiltinCiphers.aes192ctr);
     }
 }
diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256CBCTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256CBCTest.java
index dd39fd4..6503b23 100644
--- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256CBCTest.java
+++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/AES256CBCTest.java
@@ -35,7 +35,7 @@ public class AES256CBCTest extends BaseCipherTest {
     @Test
     public void testEncryptDecrypt() throws Exception {
         // for AES 256 bits we need the JCE unlimited strength policy
-        ensureKeySizeSupported(16, 32, "AES", "AES/CBC/NoPadding");
+        ensureFullCipherInformationSupported(BuiltinCiphers.aes256cbc);
         testEncryptDecrypt(BuiltinCiphers.aes256cbc);
     }
 }
diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR256Test.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR256Test.java
index 5511e0f..e9dddf8 100644
--- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR256Test.java
+++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/ARCFOUR256Test.java
@@ -35,7 +35,7 @@ public class ARCFOUR256Test extends BaseCipherTest {
     @Test
     public void testEncryptDecrypt() throws Exception {
         // for RC4 256 bits we need the JCE unlimited strength policy
-        ensureKeySizeSupported(32, "ARCFOUR", "RC4");
+        ensureCipherInformationKeySizeSupported(BuiltinCiphers.arcfour256);
         testEncryptDecrypt(BuiltinCiphers.arcfour256);
     }
 }
diff --git a/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java b/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java
index 8dc68ea..b503761 100644
--- a/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java
+++ b/sshd-common/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java
@@ -43,9 +43,17 @@ public abstract class BaseCipherTest extends JUnitTestSupport {
         super();
     }
 
-    protected void ensureKeySizeSupported(int bsize, String algorithm, String transformation) throws GeneralSecurityException {
+    protected void ensureCipherInformationKeySizeSupported(CipherInformation cipher)
+            throws GeneralSecurityException {
+        ensureKeySizeSupported(
+            cipher.getCipherBlockSize(), cipher.getAlgorithm(), cipher.getTransformation());
+    }
+
+    protected void ensureKeySizeSupported(int bsize, String algorithm, String transformation)
+            throws GeneralSecurityException {
         try {
-            javax.crypto.Cipher cipher = SecurityUtils.getCipher(transformation);
+            javax.crypto.Cipher cipher =
+                SecurityUtils.getCipher(transformation);
             byte[] key = new byte[bsize];
             cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, new SecretKeySpec(key, algorithm));
         } catch (GeneralSecurityException e) {
@@ -57,12 +65,23 @@ public abstract class BaseCipherTest extends JUnitTestSupport {
         }
     }
 
-    protected void ensureKeySizeSupported(int ivsize, int bsize, String algorithm, String transformation) throws GeneralSecurityException {
+    protected void ensureFullCipherInformationSupported(CipherInformation cipher)
+            throws GeneralSecurityException {
+        ensureKeySizeSupported(
+            cipher.getIVSize(), cipher.getCipherBlockSize(), cipher.getAlgorithm(), cipher.getTransformation());
+    }
+
+    protected void ensureKeySizeSupported(
+            int ivsize, int bsize, String algorithm, String transformation)
+                throws GeneralSecurityException {
         try {
-            javax.crypto.Cipher cipher = SecurityUtils.getCipher(transformation);
+            javax.crypto.Cipher cipher =
+                SecurityUtils.getCipher(transformation);
             byte[] key = new byte[bsize];
             byte[] iv = new byte[ivsize];
-            cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, new SecretKeySpec(key, algorithm), new IvParameterSpec(iv));
+            cipher.init(javax.crypto.Cipher.ENCRYPT_MODE,
+                new SecretKeySpec(key, algorithm),
+                new IvParameterSpec(iv));
         } catch (GeneralSecurityException e) {
             if (e instanceof InvalidKeyException) {
                 Assume.assumeTrue(algorithm + "/" + transformation + "[" + bsize + "/" + ivsize + "]", false /* force exception */);
@@ -81,15 +100,16 @@ public abstract class BaseCipherTest extends JUnitTestSupport {
         byte[] iv = new byte[ivSize];
         enc.init(Mode.Encrypt, key, iv);
 
-        byte[] expected = facName.getBytes(StandardCharsets.UTF_8);
-        byte[] workBuf = expected.clone();    // need to clone since the cipher works in-line
+        String expected = getClass().getName() + "[" + facName + "]";
+        byte[] expBytes = expected.getBytes(StandardCharsets.UTF_8);
+        byte[] workBuf = expBytes.clone();    // need to clone since the cipher works in-line
         enc.update(workBuf, 0, workBuf.length);
 
         Cipher dec = factory.create();
         dec.init(Mode.Decrypt, key, iv);
-        byte[] actual = workBuf.clone();
-        dec.update(actual, 0, actual.length);
+        byte[] actBytes = workBuf.clone();  // need to clone since the cipher works in-line
+        dec.update(actBytes, 0, actBytes.length);
 
-        assertArrayEquals(facName, expected, actual);
+        assertArrayEquals(facName, expBytes, actBytes);
     }
 }
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/PacketWriter.java b/sshd-core/src/main/java/org/apache/sshd/common/io/PacketWriter.java
index 59f66b0..1be1c88 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/io/PacketWriter.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/io/PacketWriter.java
@@ -46,11 +46,36 @@ public interface PacketWriter extends Channel {
      * @return The required padding length
      */
     static int calculatePadLength(int len, int blockSize, boolean etmMode) {
+        /*
+         * Note: according to RFC-4253 section 6:
+         *
+         *    The minimum size of a packet is 16 (or the cipher block size,
+         *     whichever is larger) bytes (plus 'mac').
+         *
+         * Since all out ciphers, MAC(s), etc. have a block size > 8 then
+         * the minimum size of the packet will be at least 16 due to the
+         * padding at the very least - so even packets that contain an opcode
+         * with no arguments will be above this value. This avoids an un-necessary
+         * call to Math.max(len, 16) for each and every packet
+         */
+
         len++;  // the pad length
         if (!etmMode) {
             len += Integer.BYTES;
         }
 
+        /*
+         * Note: according to RFC-4253 section 6:
+         *
+         *      Note that the length of the concatenation of 'packet_length',
+         *      'padding_length', 'payload', and 'random padding' MUST be a multiple
+         *      of the cipher block size or 8, whichever is larger.
+         *
+         * However, we currently do not have ciphers with a block size of less than
+         * 8 so we do not take this into account in order to accelerate the calculation
+         * and avoiding an un-necessary call to Math.max(blockSize, 8) for each and every
+         * packet.
+         */
         int pad = (-len) & (blockSize - 1);
         if (pad < blockSize) {
             pad += blockSize;
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
index 241162e..fcf2c7d 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/AbstractSession.java
@@ -161,6 +161,8 @@ public abstract class AbstractSession extends SessionHelper {
     protected int inCipherSize = 8;
     protected Mac outMac;
     protected Mac inMac;
+    protected int outMacSize;
+    protected int inMacSize;
     protected byte[] inMacResult;
     protected Compression outCompression;
     protected Compression inCompression;
@@ -197,16 +199,18 @@ public abstract class AbstractSession extends SessionHelper {
     protected long ignorePacketsFrequency = FactoryManager.DEFAULT_IGNORE_MESSAGE_FREQUENCY;
     protected int ignorePacketsVariance = FactoryManager.DEFAULT_IGNORE_MESSAGE_VARIANCE;
 
-    protected final AtomicLong maxRekeyBlocks = new AtomicLong(FactoryManager.DEFAULT_REKEY_BYTES_LIMIT / 16);
-    protected final AtomicLong ignorePacketsCount = new AtomicLong(FactoryManager.DEFAULT_IGNORE_MESSAGE_FREQUENCY);
+    protected final AtomicLong maxRekeyBlocks =
+        new AtomicLong(FactoryManager.DEFAULT_REKEY_BYTES_LIMIT / 16);
+    protected final AtomicLong ignorePacketsCount =
+        new AtomicLong(FactoryManager.DEFAULT_IGNORE_MESSAGE_FREQUENCY);
 
     /**
      * Used to wait for global requests result synchronous wait
      */
     private final AtomicReference<Object> requestResult = new AtomicReference<>();
 
-    private byte[] clientKexData;    // the payload of the client's SSH_MSG_KEXINIT
-    private byte[] serverKexData; // the payload of the factoryManager's SSH_MSG_KEXINIT
+    private byte[] clientKexData;   // the payload of the client's SSH_MSG_KEXINIT
+    private byte[] serverKexData;   // the payload of the server's SSH_MSG_KEXINIT
 
     /**
      * Create a new session.
@@ -215,7 +219,8 @@ public abstract class AbstractSession extends SessionHelper {
      * @param factoryManager the factory manager
      * @param ioSession      the underlying I/O session
      */
-    protected AbstractSession(boolean serverSession, FactoryManager factoryManager, IoSession ioSession) {
+    protected AbstractSession(
+            boolean serverSession, FactoryManager factoryManager, IoSession ioSession) {
         super(serverSession, factoryManager, ioSession);
 
         this.decoderBuffer = new SessionWorkBuffer(this);
@@ -223,15 +228,20 @@ public abstract class AbstractSession extends SessionHelper {
         attachSession(ioSession, this);
 
         Factory<Random> factory =
-            ValidateUtils.checkNotNull(factoryManager.getRandomFactory(), "No random factory for %s", ioSession);
-        random = ValidateUtils.checkNotNull(factory.create(), "No randomizer instance for %s", ioSession);
+            ValidateUtils.checkNotNull(
+                factoryManager.getRandomFactory(), "No random factory for %s", ioSession);
+        random = ValidateUtils.checkNotNull(
+            factory.create(), "No randomizer instance for %s", ioSession);
 
         refreshConfiguration();
 
         ClassLoader loader = getClass().getClassLoader();
-        sessionListenerProxy = EventListenerUtils.proxyWrapper(SessionListener.class, loader, sessionListeners);
-        channelListenerProxy = EventListenerUtils.proxyWrapper(ChannelListener.class, loader, channelListeners);
-        tunnelListenerProxy = EventListenerUtils.proxyWrapper(PortForwardingEventListener.class, loader, tunnelListeners);
+        sessionListenerProxy = EventListenerUtils.proxyWrapper(
+            SessionListener.class, loader, sessionListeners);
+        channelListenerProxy = EventListenerUtils.proxyWrapper(
+            ChannelListener.class, loader, channelListeners);
+        tunnelListenerProxy = EventListenerUtils.proxyWrapper(
+            PortForwardingEventListener.class, loader, tunnelListeners);
 
         try {
             signalSessionEstablished(ioSession);
@@ -345,19 +355,24 @@ public abstract class AbstractSession extends SessionHelper {
     protected void refreshConfiguration() {
         synchronized (random) {
             // re-keying configuration
-            maxRekeyBytes = this.getLongProperty(FactoryManager.REKEY_BYTES_LIMIT, maxRekeyBytes);
-            maxRekeyInterval = this.getLongProperty(FactoryManager.REKEY_TIME_LIMIT, maxRekeyInterval);
-            maxRekyPackets = this.getLongProperty(FactoryManager.REKEY_PACKETS_LIMIT, maxRekyPackets);
+            maxRekeyBytes = getLongProperty(FactoryManager.REKEY_BYTES_LIMIT, maxRekeyBytes);
+            maxRekeyInterval = getLongProperty(FactoryManager.REKEY_TIME_LIMIT, maxRekeyInterval);
+            maxRekyPackets = getLongProperty(FactoryManager.REKEY_PACKETS_LIMIT, maxRekyPackets);
 
             // intermittent SSH_MSG_IGNORE stream padding
-            ignorePacketDataLength = this.getIntProperty(FactoryManager.IGNORE_MESSAGE_SIZE, FactoryManager.DEFAULT_IGNORE_MESSAGE_SIZE);
-            ignorePacketsFrequency = this.getLongProperty(FactoryManager.IGNORE_MESSAGE_FREQUENCY, FactoryManager.DEFAULT_IGNORE_MESSAGE_FREQUENCY);
-            ignorePacketsVariance = this.getIntProperty(FactoryManager.IGNORE_MESSAGE_VARIANCE, FactoryManager.DEFAULT_IGNORE_MESSAGE_VARIANCE);
+            ignorePacketDataLength = getIntProperty(
+                FactoryManager.IGNORE_MESSAGE_SIZE, FactoryManager.DEFAULT_IGNORE_MESSAGE_SIZE);
+            ignorePacketsFrequency = getLongProperty(
+                FactoryManager.IGNORE_MESSAGE_FREQUENCY, FactoryManager.DEFAULT_IGNORE_MESSAGE_FREQUENCY);
+            ignorePacketsVariance = getIntProperty(
+                FactoryManager.IGNORE_MESSAGE_VARIANCE, FactoryManager.DEFAULT_IGNORE_MESSAGE_VARIANCE);
             if (ignorePacketsVariance >= ignorePacketsFrequency) {
                 ignorePacketsVariance = 0;
             }
 
-            ignorePacketsCount.set(calculateNextIgnorePacketCount(random, ignorePacketsFrequency, ignorePacketsVariance));
+            long countValue = calculateNextIgnorePacketCount(
+                random, ignorePacketsFrequency, ignorePacketsVariance);
+            ignorePacketsCount.set(countValue);
         }
     }
 
@@ -399,7 +414,8 @@ public abstract class AbstractSession extends SessionHelper {
     protected void doHandleMessage(Buffer buffer) throws Exception {
         int cmd = buffer.getUByte();
         if (log.isTraceEnabled()) {
-            log.trace("doHandleMessage({}) process {}", this, SshConstants.getCommandMessageName(cmd));
+            log.trace("doHandleMessage({}) process {}",
+                this, SshConstants.getCommandMessageName(cmd));
         }
 
         switch (cmd) {
@@ -541,7 +557,8 @@ public abstract class AbstractSession extends SessionHelper {
          *          + As the next packet following the server's first SSH_MSG_NEWKEYS.
          */
         KexExtensionHandler extHandler = getKexExtensionHandler();
-        if ((extHandler == null) || (!extHandler.isKexExtensionsAvailable(this, AvailabilityPhase.NEWKEYS))) {
+        if ((extHandler == null)
+                || (!extHandler.isKexExtensionsAvailable(this, AvailabilityPhase.NEWKEYS))) {
             return future;
         }
 
@@ -555,14 +572,16 @@ public abstract class AbstractSession extends SessionHelper {
         boolean debugEnabled = log.isDebugEnabled();
         if (kex.next(cmd, buffer)) {
             if (debugEnabled) {
-                log.debug("handleKexMessage({})[{}] KEX processing complete after cmd={}", this, kex.getName(), cmd);
+                log.debug("handleKexMessage({})[{}] KEX processing complete after cmd={}",
+                    this, kex.getName(), cmd);
             }
             checkKeys();
             sendNewKeys();
             kexState.set(KexState.KEYS);
         } else {
             if (debugEnabled) {
-                log.debug("handleKexMessage({})[{}] more KEX packets expected after cmd={}", this, kex.getName(), cmd);
+                log.debug("handleKexMessage({})[{}] more KEX packets expected after cmd={}",
+                    this, kex.getName(), cmd);
             }
         }
     }
@@ -620,7 +639,8 @@ public abstract class AbstractSession extends SessionHelper {
             log.debug("handleServiceRequest({}) Accepted service {}", this, serviceName);
         }
 
-        Buffer response = createBuffer(SshConstants.SSH_MSG_SERVICE_ACCEPT, Byte.SIZE + GenericUtils.length(serviceName));
+        Buffer response = createBuffer(
+            SshConstants.SSH_MSG_SERVICE_ACCEPT, Byte.SIZE + GenericUtils.length(serviceName));
         response.putString(serviceName);
         writePacket(response);
         return true;
@@ -747,8 +767,9 @@ public abstract class AbstractSession extends SessionHelper {
     protected void validateKexState(int cmd, KexState expected) {
         KexState actual = kexState.get();
         if (!expected.equals(actual)) {
-            throw new IllegalStateException("Received KEX command=" + SshConstants.getCommandMessageName(cmd)
-                  + " while in state=" + actual + " instead of " + expected);
+            throw new IllegalStateException(
+                "Received KEX command=" + SshConstants.getCommandMessageName(cmd)
+              + " while in state=" + actual + " instead of " + expected);
         }
     }
 
@@ -803,7 +824,8 @@ public abstract class AbstractSession extends SessionHelper {
     @Override
     public <T extends Service> T getService(Class<T> clazz) {
         Collection<? extends Service> registeredServices = getServices();
-        ValidateUtils.checkState(GenericUtils.isNotEmpty(registeredServices), "No registered services to look for %s", clazz.getSimpleName());
+        ValidateUtils.checkState(GenericUtils.isNotEmpty(registeredServices),
+            "No registered services to look for %s", clazz.getSimpleName());
 
         for (Service s : registeredServices) {
             if (clazz.isInstance(s)) {
@@ -822,9 +844,10 @@ public abstract class AbstractSession extends SessionHelper {
             int cmd = bufData[buffer.rpos()] & 0xFF;
             if (cmd > SshConstants.SSH_MSG_KEX_LAST) {
                 String cmdName = SshConstants.getCommandMessageName(cmd);
+                boolean debugEnabled = log.isDebugEnabled();
                 synchronized (pendingPackets) {
                     if (!KexState.DONE.equals(kexState.get())) {
-                        if (pendingPackets.isEmpty()) {
+                        if (pendingPackets.isEmpty() && debugEnabled) {
                             log.debug("writePacket({})[{}] Start flagging packets as pending until key exchange is done", this, cmdName);
                         }
                         PendingWriteFuture future = new PendingWriteFuture(cmdName, buffer);
@@ -898,7 +921,9 @@ public abstract class AbstractSession extends SessionHelper {
     }
 
     protected int resolveIgnoreBufferDataLength() {
-        if ((ignorePacketDataLength <= 0) || (ignorePacketsFrequency <= 0L) || (ignorePacketsVariance < 0)) {
+        if ((ignorePacketDataLength <= 0)
+                || (ignorePacketsFrequency <= 0L)
+                || (ignorePacketsVariance < 0)) {
             return 0;
         }
 
@@ -908,7 +933,8 @@ public abstract class AbstractSession extends SessionHelper {
         }
 
         synchronized (random) {
-            count = calculateNextIgnorePacketCount(random, ignorePacketsFrequency, ignorePacketsVariance);
+            count = calculateNextIgnorePacketCount(
+                random, ignorePacketsFrequency, ignorePacketsVariance);
             ignorePacketsCount.set(count);
             return ignorePacketDataLength + random.random(ignorePacketDataLength);
         }
@@ -990,16 +1016,11 @@ public abstract class AbstractSession extends SessionHelper {
         // Since the caller claims to know how many bytes they will need
         // increase their request to account for our headers/footers if
         // they actually send exactly this amount.
-        //
-        int bsize = outCipherSize;
-        len += SshConstants.SSH_PACKET_HEADER_LEN;
-        int pad = (-len) & (bsize - 1);
-        if (pad < bsize) {
-            pad += bsize;
-        }
-        len = len + pad - 4;
+        boolean etmMode = (outMac == null) ? false : outMac.isEncryptThenMac();
+        int pad = PacketWriter.calculatePadLength(len, outCipherSize, etmMode);
+        len = SshConstants.SSH_PACKET_HEADER_LEN + len + pad + Byte.BYTES /* the pad length byte */;
         if (outMac != null) {
-            len += outMac.getBlockSize();
+            len += outMacSize;
         }
 
         return prepareBuffer(cmd, new ByteArrayBuffer(new byte[len + Byte.SIZE], false));
@@ -1026,8 +1047,10 @@ public abstract class AbstractSession extends SessionHelper {
      */
     protected <B extends Buffer> B validateTargetBuffer(int cmd, B buffer) {
         ValidateUtils.checkNotNull(buffer, "No target buffer to examine for command=%d", cmd);
-        ValidateUtils.checkTrue(buffer != decoderBuffer, "Not allowed to use the internal decoder buffer for command=%d", cmd);
-        ValidateUtils.checkTrue(buffer != uncompressBuffer, "Not allowed to use the internal uncompress buffer for command=%d", cmd);
+        ValidateUtils.checkTrue(
+            buffer != decoderBuffer, "Not allowed to use the internal decoder buffer for command=%d", cmd);
+        ValidateUtils.checkTrue(
+            buffer != uncompressBuffer, "Not allowed to use the internal uncompress buffer for command=%d", cmd);
         return buffer;
     }
 
@@ -1068,7 +1091,8 @@ public abstract class AbstractSession extends SessionHelper {
             // Debug log the packet
             boolean traceEnabled = log.isTraceEnabled();
             if (traceEnabled) {
-                buffer.dumpHex(getSimplifiedLogger(), Level.FINEST, "encode(" + this + ") packet #" + seqo, this);
+                buffer.dumpHex(getSimplifiedLogger(), Level.FINEST,
+                    "encode(" + this + ") packet #" + seqo, this);
             }
 
             // Compress the packet if needed
@@ -1116,9 +1140,11 @@ public abstract class AbstractSession extends SessionHelper {
 
             // Increment packet id
             seqo = (seqo + 1L) & 0x0ffffffffL;
-            // Update stats
+
+            // Update counters used to track re-keying
             outPacketsCount.incrementAndGet();
             outBytesCount.addAndGet(len);
+
             // Make buffer ready to be read
             buffer.rpos(off);
             return buffer;
@@ -1134,10 +1160,9 @@ public abstract class AbstractSession extends SessionHelper {
             return;
         }
 
-        int macSize = outMac.getBlockSize();
         int l = buf.wpos();
         // ensure enough room for MAC in outgoing buffer
-        buf.wpos(l + macSize);
+        buf.wpos(l + outMacSize);
         // Include sequence number
         outMac.updateUInt(seqo);
         // Include the length field in the MAC calculation
@@ -1152,7 +1177,7 @@ public abstract class AbstractSession extends SessionHelper {
         }
         outCipher.update(buf.array(), offset, len);
 
-        int blocksCount = len / outCipher.getCipherBlockSize();
+        int blocksCount = len / outCipherSize;
         outBlocksCount.addAndGet(Math.max(1, blocksCount));
     }
 
@@ -1169,10 +1194,19 @@ public abstract class AbstractSession extends SessionHelper {
             if (decoderState == 0) {
                 // The read position should always be 0 at this point because we have compacted this buffer
                 assert decoderBuffer.rpos() == 0;
+                /*
+                 * Note: according to RFC-4253 section 6:
+                 *
+                 *      Implementations SHOULD decrypt the length after receiving
+                 *      the first 8 (or cipher block size  whichever is larger) bytes
+                 *
+                 * However, we currently do not have ciphers with a block size of less than
+                 * 8 we avoid un-necessary Math.max(minBufLen, 8) for each and every packet
+                 */
                 int minBufLen = etmMode ? Integer.BYTES : inCipherSize;
                 // If we have received enough bytes, start processing those
                 if (decoderBuffer.available() > minBufLen) {
-                    // Decrypt the first bytes
+                    // Decrypt the first bytes so we can extract the packet length
                     if ((inCipher != null) && (!etmMode)) {
                         inCipher.update(decoderBuffer.array(), 0, inCipherSize);
 
@@ -1188,7 +1222,8 @@ public abstract class AbstractSession extends SessionHelper {
                     if ((decoderLength < SshConstants.SSH_PACKET_HEADER_LEN)
                             || (decoderLength > (8 * SshConstants.SSH_REQUIRED_PAYLOAD_PACKET_LENGTH_SUPPORT))) {
                         log.warn("decode({}) Error decoding packet(invalid length): {}", this, decoderLength);
-                        decoderBuffer.dumpHex(getSimplifiedLogger(), Level.FINEST, "decode(" + this + ") invalid length packet", this);
+                        decoderBuffer.dumpHex(getSimplifiedLogger(), Level.FINEST,
+                            "decode(" + this + ") invalid length packet", this);
                         throw new SshException(SshConstants.SSH2_DISCONNECT_PROTOCOL_ERROR,
                                 "Invalid packet length: " + decoderLength);
                     }
@@ -1202,7 +1237,7 @@ public abstract class AbstractSession extends SessionHelper {
             } else if (decoderState == 1) {
                 // The read position should always be after reading the packet length at this point
                 assert decoderBuffer.rpos() == Integer.BYTES;
-                int macSize = (inMac != null) ? inMac.getBlockSize() : 0;
+                int macSize = (inMac != null) ? inMacSize : 0;
                 // Check if the packet has been fully received
                 if (decoderBuffer.available() >= (decoderLength + macSize)) {
                     byte[] data = decoderBuffer.array();
@@ -1210,18 +1245,21 @@ public abstract class AbstractSession extends SessionHelper {
                         validateIncomingMac(data, 0, decoderLength + Integer.BYTES);
 
                         if (inCipher != null) {
-                            inCipher.update(data, Integer.BYTES, decoderLength);
+                            inCipher.update(data, Integer.BYTES /* packet length is unencrypted */, decoderLength);
 
-                            int blocksCount = decoderLength / inCipher.getCipherBlockSize();
+                            int blocksCount = decoderLength / inCipherSize;
                             inBlocksCount.addAndGet(Math.max(1, blocksCount));
                         }
                     } else {
-                        // Decrypt the remaining of the packet
+                        /*
+                         * Decrypt the remaining of the packet - skip the block we
+                         * already decoded in order to extract the packet length
+                         */
                         if (inCipher != null) {
                             int updateLen = decoderLength + Integer.BYTES - inCipherSize;
                             inCipher.update(data, inCipherSize, updateLen);
 
-                            int blocksCount = updateLen / inCipher.getCipherBlockSize();
+                            int blocksCount = updateLen / inCipherSize;
                             inBlocksCount.addAndGet(Math.max(1, blocksCount));
                         }
 
@@ -1230,6 +1268,7 @@ public abstract class AbstractSession extends SessionHelper {
 
                     // Increment incoming packet sequence number
                     seqi = (seqi + 1L) & 0x0ffffffffL;
+
                     // Get padding
                     int pad = decoderBuffer.getUByte();
                     Buffer packet;
@@ -1253,14 +1292,17 @@ public abstract class AbstractSession extends SessionHelper {
                     }
 
                     if (log.isTraceEnabled()) {
-                        packet.dumpHex(getSimplifiedLogger(), Level.FINEST, "decode(" + this + ") packet #" + seqi, this);
+                        packet.dumpHex(getSimplifiedLogger(), Level.FINEST,
+                            "decode(" + this + ") packet #" + seqi, this);
                     }
 
-                    // Update stats
+                    // Update counters used to track re-keying
                     inPacketsCount.incrementAndGet();
                     inBytesCount.addAndGet(packet.available());
+
                     // Process decoded packet
                     handleMessage(packet);
+
                     // Set ready to handle next packet
                     decoderBuffer.rpos(decoderLength + Integer.BYTES + macSize);
                     decoderBuffer.wpos(wpos);
@@ -1287,7 +1329,7 @@ public abstract class AbstractSession extends SessionHelper {
         inMac.doFinal(inMacResult, 0);
 
         // Check the computed result with the received mac (just after the packet data)
-        if (!BufferUtils.equals(inMacResult, 0, data, offset + len, inMac.getBlockSize())) {
+        if (!BufferUtils.equals(inMacResult, 0, data, offset + len, inMacSize)) {
             throw new SshException(SshConstants.SSH2_DISCONNECT_MAC_ERROR, "MAC Error");
         }
     }
@@ -1475,7 +1517,8 @@ public abstract class AbstractSession extends SessionHelper {
 
         boolean serverSession = isServerSession();
         String value = getNegotiatedKexParameter(KexProposalOption.S2CENC);
-        Cipher s2ccipher = ValidateUtils.checkNotNull(NamedFactory.create(getCipherFactories(), value), "Unknown s2c cipher: %s", value);
+        Cipher s2ccipher = ValidateUtils.checkNotNull(
+            NamedFactory.create(getCipherFactories(), value), "Unknown s2c cipher: %s", value);
         e_s2c = resizeKey(e_s2c, s2ccipher.getKdfSize(), hash, k, h);
         s2ccipher.init(serverSession ? Cipher.Mode.Encrypt : Cipher.Mode.Decrypt, e_s2c, iv_s2c);
 
@@ -1494,7 +1537,8 @@ public abstract class AbstractSession extends SessionHelper {
         }
 
         value = getNegotiatedKexParameter(KexProposalOption.C2SENC);
-        Cipher c2scipher = ValidateUtils.checkNotNull(NamedFactory.create(getCipherFactories(), value), "Unknown c2s cipher: %s", value);
+        Cipher c2scipher = ValidateUtils.checkNotNull(
+            NamedFactory.create(getCipherFactories(), value), "Unknown c2s cipher: %s", value);
         e_c2s = resizeKey(e_c2s, c2scipher.getKdfSize(), hash, k, h);
         c2scipher.init(serverSession ? Cipher.Mode.Decrypt : Cipher.Mode.Encrypt, e_c2s, iv_c2s);
 
@@ -1527,22 +1571,26 @@ public abstract class AbstractSession extends SessionHelper {
             inMac = s2cmac;
             inCompression = s2ccomp;
         }
-        outCipherSize = outCipher.getIVSize();
+
+        outCipherSize = outCipher.getCipherBlockSize();
+        outMacSize = outMac.getBlockSize();
         // TODO add support for configurable compression level
         outCompression.init(Compression.Type.Deflater, -1);
 
-        inCipherSize = inCipher.getIVSize();
-        inMacResult = new byte[inMac.getBlockSize()];
+        inCipherSize = inCipher.getCipherBlockSize();
+        inMacSize = inMac.getBlockSize();
+        inMacResult = new byte[inMacSize];
         // TODO add support for configurable compression level
         inCompression.init(Compression.Type.Inflater, -1);
 
         // see https://tools.ietf.org/html/rfc4344#section-3.2
-        int inBlockSize = inCipher.getCipherBlockSize();
-        int outBlockSize = outCipher.getCipherBlockSize();
         // select the lowest cipher size
-        int avgCipherBlockSize = Math.min(inBlockSize, outBlockSize);
-        long recommendedByteRekeyBlocks = 1L << Math.min((avgCipherBlockSize * Byte.SIZE) / 4, 63);    // in case (block-size / 4) > 63
-        maxRekeyBlocks.set(this.getLongProperty(FactoryManager.REKEY_BLOCKS_LIMIT, recommendedByteRekeyBlocks));
+        int avgCipherBlockSize = Math.min(inCipherSize, outCipherSize);
+        long recommendedByteRekeyBlocks =
+            1L << Math.min((avgCipherBlockSize * Byte.SIZE) / 4, 63);    // in case (block-size / 4) > 63
+        long effectiveRekyBlocksCount =
+            getLongProperty(FactoryManager.REKEY_BLOCKS_LIMIT, recommendedByteRekeyBlocks);
+        maxRekeyBlocks.set(effectiveRekyBlocksCount);
         if (debugEnabled) {
             log.debug("receiveNewKeys({}) inCipher={}, outCipher={}, recommended blocks limit={}, actual={}",
                   this, inCipher, outCipher, recommendedByteRekeyBlocks, maxRekeyBlocks);
@@ -1984,7 +2032,8 @@ public abstract class AbstractSession extends SessionHelper {
             return false;   // disabled
         }
 
-        boolean rekey = (inPacketsCount.get() > maxRekyPackets) || (outPacketsCount.get() > maxRekyPackets);
+        boolean rekey = (inPacketsCount.get() > maxRekyPackets)
+            || (outPacketsCount.get() > maxRekyPackets);
         if (rekey) {
             if (log.isDebugEnabled()) {
                 log.debug("isRekeyPacketCountsExceeded({}) re-keying: in={}, out={}, max={}",
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java
index 3a24647..d18d803 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/helpers/SessionHelper.java
@@ -687,7 +687,9 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
      * @return the resized key
      * @throws Exception if a problem occur while resizing the key
      */
-    protected byte[] resizeKey(byte[] e, int kdfSize, Digest hash, byte[] k, byte[] h) throws Exception {
+    protected byte[] resizeKey(
+            byte[] e, int kdfSize, Digest hash, byte[] k, byte[] h)
+                throws Exception {
         for (Buffer buffer = null; kdfSize > e.length; buffer = BufferUtils.clear(buffer)) {
             if (buffer == null) {
                 buffer = new ByteArrayBuffer();
@@ -697,12 +699,14 @@ public abstract class SessionHelper extends AbstractKexFactoryManager implements
             buffer.putRawBytes(h);
             buffer.putRawBytes(e);
             hash.update(buffer.array(), 0, buffer.available());
+
             byte[] foo = hash.digest();
             byte[] bar = new byte[e.length + foo.length];
             System.arraycopy(e, 0, bar, 0, e.length);
             System.arraycopy(foo, 0, bar, e.length, foo.length);
             e = bar;
         }
+
         return e;
     }
 
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/cipher/BuiltinCiphersTest.java b/sshd-core/src/test/java/org/apache/sshd/common/cipher/BuiltinCiphersTest.java
index 394fff5..efb7f60 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/cipher/BuiltinCiphersTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/cipher/BuiltinCiphersTest.java
@@ -201,7 +201,8 @@ public class BuiltinCiphersTest extends BaseTestSupport {
     @Test
     public void testParseCiphersList() {
         List<String> builtin = NamedResource.getNameList(BuiltinCiphers.VALUES);
-        List<String> unknown = Arrays.asList(getClass().getPackage().getName(), getClass().getSimpleName(), getCurrentTestName());
+        List<String> unknown = Arrays.asList(
+            getClass().getPackage().getName(), getClass().getSimpleName(), getCurrentTestName());
         Random rnd = new Random();
         for (int index = 0; index < (builtin.size() + unknown.size()); index++) {
             Collections.shuffle(builtin, rnd);
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java b/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java
index 949e3df..e9c3d09 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/cipher/CipherTest.java
@@ -71,10 +71,13 @@ public class CipherTest extends BaseTestSupport {
         Collections.unmodifiableList(
             Arrays.asList(
                 new Object[]{BuiltinCiphers.aes128cbc, com.jcraft.jsch.jce.AES128CBC.class, NUM_LOADTEST_ROUNDS},
+                new Object[]{BuiltinCiphers.aes128ctr, com.jcraft.jsch.jce.AES128CTR.class, NUM_LOADTEST_ROUNDS},
                 new Object[]{BuiltinCiphers.tripledescbc, com.jcraft.jsch.jce.TripleDESCBC.class, NUM_LOADTEST_ROUNDS},
                 new Object[]{BuiltinCiphers.blowfishcbc, com.jcraft.jsch.jce.BlowfishCBC.class, NUM_LOADTEST_ROUNDS},
                 new Object[]{BuiltinCiphers.aes192cbc, com.jcraft.jsch.jce.AES192CBC.class, NUM_LOADTEST_ROUNDS},
+                new Object[]{BuiltinCiphers.aes192ctr, com.jcraft.jsch.jce.AES192CTR.class, NUM_LOADTEST_ROUNDS},
                 new Object[]{BuiltinCiphers.aes256cbc, com.jcraft.jsch.jce.AES256CBC.class, NUM_LOADTEST_ROUNDS},
+                new Object[]{BuiltinCiphers.aes256ctr, com.jcraft.jsch.jce.AES256CTR.class, NUM_LOADTEST_ROUNDS},
                 new Object[]{BuiltinCiphers.arcfour128, com.jcraft.jsch.jce.ARCFOUR128.class, NUM_LOADTEST_ROUNDS},
                 new Object[]{BuiltinCiphers.arcfour256, com.jcraft.jsch.jce.ARCFOUR256.class, NUM_LOADTEST_ROUNDS}
             ));
@@ -94,7 +97,10 @@ public class CipherTest extends BaseTestSupport {
     private final Class<? extends com.jcraft.jsch.Cipher> jschCipher;
     private final int loadTestRounds;
 
-    public CipherTest(BuiltinCiphers builtInCipher, Class<? extends com.jcraft.jsch.Cipher> jschCipher, int loadTestRounds) {
+    public CipherTest(
+            BuiltinCiphers builtInCipher,
+            Class<? extends com.jcraft.jsch.Cipher> jschCipher,
+            int loadTestRounds) {
         this.builtInCipher = builtInCipher;
         this.jschCipher = jschCipher;
         this.loadTestRounds = loadTestRounds;
@@ -126,7 +132,8 @@ public class CipherTest extends BaseTestSupport {
 
     @Test
     public void testBuiltinCipherSession() throws Exception {
-        Assume.assumeTrue("No internal support for " + builtInCipher.getName(), builtInCipher.isSupported() && checkCipher(jschCipher.getName()));
+        Assume.assumeTrue("No internal support for " + builtInCipher.getName(),
+            builtInCipher.isSupported() && checkCipher(jschCipher.getName()));
         sshd.setCipherFactories(Collections.singletonList(builtInCipher));
         runJschTest(port);
     }
@@ -170,7 +177,9 @@ public class CipherTest extends BaseTestSupport {
         loadTest(builtInCipher, random, loadTestRounds);
     }
 
-    private static void loadTest(NamedFactory<Cipher> factory, Random random, int numRounds) throws Exception {
+    private static void loadTest(
+            NamedFactory<Cipher> factory, Random random, int numRounds)
+                throws Exception {
         Cipher cipher = factory.create();
         byte[] key = new byte[cipher.getKdfSize()];
         byte[] iv = new byte[cipher.getIVSize()];
@@ -185,7 +194,10 @@ public class CipherTest extends BaseTestSupport {
             cipher.update(input, 0, input.length);
         }
         long t1 = System.currentTimeMillis();
-        System.err.println(factory.getName() + "[" + numRounds + "]: " + (t1 - t0) + " ms");
+        System.err.append(CipherTest.class.getSimpleName())
+            .append(" - ").append(factory.getName())
+            .append('[').append(Integer.toString(numRounds)).append(']')
+            .append(": ").append(Long.toString(t1 - t0)).println(" ms");
     }
 
     static boolean checkCipher(String cipher) {
@@ -197,7 +209,9 @@ public class CipherTest extends BaseTestSupport {
                     new byte[jschCipher.getIVSize()]);
             return true;
         } catch (Exception e) {
-            System.err.println("checkCipher(" + cipher + ") " + e.getClass().getSimpleName() + ": " + e.getMessage());
+            System.err.println("checkCipher(" + cipher + ")"
+                + " " + e.getClass().getSimpleName()
+                + ": " + e.getMessage());
             return false;
         }
     }


[mina-sshd] 07/07: [SSHD-842] Updated hierarchy of ServerSessionHolder(s)

Posted by lg...@apache.org.
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 32f9eb6943dd8abc19a23dfd70fd60e8d3f558e2
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Oct 17 13:50:49 2019 +0300

    [SSHD-842] Updated hierarchy of ServerSessionHolder(s)
---
 .../sshd/client/session/ClientUserAuthService.java | 21 ++++++++-------
 .../main/java/org/apache/sshd/common/Service.java  |  5 ++--
 .../java/org/apache/sshd/server/auth/UserAuth.java |  1 -
 .../sshd/server/channel/AbstractServerChannel.java |  7 -----
 .../apache/sshd/server/channel/ServerChannel.java  |  6 ++++-
 .../server/command/AbstractCommandSupport.java     | 31 +++++++++++++++-------
 .../server/kex/AbstractDHServerKeyExchange.java    | 12 ++++++---
 .../apache/sshd/server/shell/InvertedShell.java    | 15 ++++++++++-
 .../org/apache/sshd/server/shell/ProcessShell.java | 23 +++++++++-------
 .../server/shell/InvertedShellWrapperTest.java     | 28 ++++++++++++++++---
 .../apache/sshd/util/test/BogusInvertedShell.java  |  4 +--
 .../subsystem/sftp/SftpSubsystemEnvironment.java   |  9 ++++++-
 12 files changed, 108 insertions(+), 54 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientUserAuthService.java b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientUserAuthService.java
index cccbc87..5c00c6a 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientUserAuthService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientUserAuthService.java
@@ -41,7 +41,6 @@ import org.apache.sshd.common.SshConstants;
 import org.apache.sshd.common.SshException;
 import org.apache.sshd.common.auth.UserAuthMethodFactory;
 import org.apache.sshd.common.session.Session;
-import org.apache.sshd.common.session.SessionHolder;
 import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.ValidateUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
@@ -52,10 +51,7 @@ import org.apache.sshd.common.util.closeable.AbstractCloseable;
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public class ClientUserAuthService
-        extends AbstractCloseable
-        implements Service, SessionHolder<ClientSession>, ClientSessionHolder {
-
+public class ClientUserAuthService extends AbstractCloseable implements Service, ClientSessionHolder {
     /**
      * The AuthFuture that is being used by the current auth request. This encodes the state.
      * isSuccess -> authenticated, else if isDone -> server waiting for user auth, else authenticating.
@@ -144,7 +140,8 @@ public class ClientUserAuthService
                     log.debug("auth({})[{}] request new authentication", session, service);
                 }
             } else {
-                currentFuture.setException(new InterruptedIOException("New authentication started before previous completed"));
+                currentFuture.setException(
+                    new InterruptedIOException("New authentication started before previous completed"));
             }
         }
 
@@ -240,7 +237,8 @@ public class ClientUserAuthService
             session.setAuthenticated();
             ((ClientSessionImpl) session).switchToNextService();
 
-            AuthFuture authFuture = Objects.requireNonNull(authFutureHolder.get(), "No current future");
+            AuthFuture authFuture =
+                Objects.requireNonNull(authFutureHolder.get(), "No current future");
             // Will wake up anyone sitting in waitFor
             authFuture.setAuthed(true);
             return;
@@ -270,7 +268,8 @@ public class ClientUserAuthService
         }
 
         if (userAuth == null) {
-            throw new IllegalStateException("Received unknown packet: " + SshConstants.getCommandMessageName(cmd));
+            throw new IllegalStateException(
+                "Received unknown packet: " + SshConstants.getCommandMessageName(cmd));
         }
 
         if (log.isDebugEnabled()) {
@@ -328,9 +327,11 @@ public class ClientUserAuthService
                 }
 
                 // also wake up anyone sitting in waitFor
-                AuthFuture authFuture = Objects.requireNonNull(authFutureHolder.get(), "No current future");
+                AuthFuture authFuture =
+                    Objects.requireNonNull(authFutureHolder.get(), "No current future");
                 authFuture.setException(new SshException(
-                    SshConstants.SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE, "No more authentication methods available"));
+                    SshConstants.SSH2_DISCONNECT_NO_MORE_AUTH_METHODS_AVAILABLE,
+                    "No more authentication methods available"));
                 return;
             }
 
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/Service.java b/sshd-core/src/main/java/org/apache/sshd/common/Service.java
index 69426e9..2ebc41c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/Service.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/Service.java
@@ -19,6 +19,7 @@
 package org.apache.sshd.common;
 
 import org.apache.sshd.common.session.Session;
+import org.apache.sshd.common.session.SessionHolder;
 import org.apache.sshd.common.util.buffer.Buffer;
 
 /**
@@ -27,9 +28,7 @@ import org.apache.sshd.common.util.buffer.Buffer;
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public interface Service extends PropertyResolver, Closeable {
-    Session getSession();
-
+public interface Service extends SessionHolder<Session>, PropertyResolver, Closeable {
     @Override
     default PropertyResolver getParentPropertyResolver() {
         return getSession();
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/auth/UserAuth.java b/sshd-core/src/main/java/org/apache/sshd/server/auth/UserAuth.java
index d26da38..21a92ab 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/auth/UserAuth.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/auth/UserAuth.java
@@ -30,7 +30,6 @@ import org.apache.sshd.server.session.ServerSessionHolder;
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public interface UserAuth extends ServerSessionHolder, UserAuthInstance<ServerSession>, UsernameHolder {
-
     /**
      * Try to authenticate the user. This methods should return a non {@code null}
      * value indicating if the authentication succeeded. If the authentication is
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java b/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java
index aa42934..250e818 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/channel/AbstractServerChannel.java
@@ -36,7 +36,6 @@ import org.apache.sshd.common.session.Session;
 import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.threads.CloseableExecutorService;
-import org.apache.sshd.server.session.ServerSession;
 
 /**
  * TODO Add javadoc
@@ -44,7 +43,6 @@ import org.apache.sshd.server.session.ServerSession;
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public abstract class AbstractServerChannel extends AbstractChannel implements ServerChannel {
-
     protected final AtomicBoolean exitStatusSent = new AtomicBoolean(false);
 
     protected AbstractServerChannel(CloseableExecutorService executor) {
@@ -58,11 +56,6 @@ public abstract class AbstractServerChannel extends AbstractChannel implements S
     }
 
     @Override
-    public ServerSession getServerSession() {
-        return (ServerSession) getSession();
-    }
-
-    @Override
     public OpenFuture open(int recipient, long rwSize, long packetSize, Buffer buffer) {
         setRecipient(recipient);
 
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/channel/ServerChannel.java b/sshd-core/src/main/java/org/apache/sshd/server/channel/ServerChannel.java
index 5dc73de..b3e75c4 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/channel/ServerChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/channel/ServerChannel.java
@@ -20,11 +20,15 @@
 package org.apache.sshd.server.channel;
 
 import org.apache.sshd.common.channel.Channel;
+import org.apache.sshd.server.session.ServerSession;
 import org.apache.sshd.server.session.ServerSessionHolder;
 
 /**
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public interface ServerChannel extends Channel, ServerSessionHolder {
-    // Marker interface
+    @Override
+    default ServerSession getServerSession() {
+        return (ServerSession) getSession();
+    }
 }
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/command/AbstractCommandSupport.java b/sshd-core/src/main/java/org/apache/sshd/server/command/AbstractCommandSupport.java
index 67a636a..03d1e3f 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/command/AbstractCommandSupport.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/command/AbstractCommandSupport.java
@@ -47,7 +47,7 @@ import org.apache.sshd.server.session.ServerSessionHolder;
 public abstract class AbstractCommandSupport
         extends AbstractLoggingBean
         implements Command, Runnable, ExecutorServiceCarrier, SessionAware,
-                    SessionHolder<Session>, ServerSessionHolder {
+        SessionHolder<ServerSession>, ServerSessionHolder {
     protected final String command;
     protected InputStream in;
     protected OutputStream out;
@@ -55,7 +55,7 @@ public abstract class AbstractCommandSupport
     protected ExitCallback callback;
     protected Environment environment;
     protected Future<?> cmdFuture;
-    protected Thread cmdRunner;
+    protected volatile Thread cmdRunner;
     protected CloseableExecutorService executorService;
     protected boolean cbCalled;
     protected ServerSession serverSession;
@@ -78,7 +78,7 @@ public abstract class AbstractCommandSupport
     }
 
     @Override
-    public Session getSession() {
+    public ServerSession getSession() {
         return getServerSession();
     }
 
@@ -145,13 +145,19 @@ public abstract class AbstractCommandSupport
     public void start(ChannelSession channel, Environment env) throws IOException {
         environment = env;
         try {
+            if (log.isDebugEnabled()) {
+                log.debug("start({}) starting runner for command={}", channel, command);
+            }
+
             CloseableExecutorService executors = getExecutorService();
             cmdFuture = executors.submit(() -> {
                 cmdRunner = Thread.currentThread();
                 this.run();
             });
         } catch (RuntimeException e) {    // e.g., RejectedExecutionException
-            log.error("Failed (" + e.getClass().getSimpleName() + ") to start command=" + command + ": " + e.getMessage(), e);
+            log.error("start(" + channel + ")"
+                + " Failed (" + e.getClass().getSimpleName() + ")"
+                + " to start command=" + command + ": " + e.getMessage(), e);
             throw new IOException(e);
         }
     }
@@ -160,11 +166,13 @@ public abstract class AbstractCommandSupport
     public void destroy(ChannelSession channel) throws Exception {
         // if thread has not completed, cancel it
         boolean debugEnabled = log.isDebugEnabled();
-        if ((cmdFuture != null) && (!cmdFuture.isDone()) && (cmdRunner != Thread.currentThread())) {
+        if ((cmdFuture != null)
+                && (!cmdFuture.isDone())
+                && (cmdRunner != Thread.currentThread())) {
             boolean result = cmdFuture.cancel(true);
             // TODO consider waiting some reasonable (?) amount of time for cancellation
             if (debugEnabled) {
-                log.debug("destroy() - cancel pending future=" + result);
+                log.debug("destroy({})[{}] - cancel pending future={}", channel, this, result);
             }
         }
 
@@ -174,7 +182,8 @@ public abstract class AbstractCommandSupport
         if ((executors != null) && (!executors.isShutdown())) {
             Collection<Runnable> runners = executors.shutdownNow();
             if (debugEnabled) {
-                log.debug("destroy() - shutdown executor service - runners count=" + runners.size());
+                log.debug("destroy({})[{}] - shutdown executor service - runners count={}",
+                    channel, this, runners.size());
             }
         }
         this.executorService = null;
@@ -185,10 +194,11 @@ public abstract class AbstractCommandSupport
     }
 
     protected void onExit(int exitValue, String exitMessage) {
+        Session session = getSession();
         if (cbCalled) {
             if (log.isTraceEnabled()) {
-                log.trace("onExit({}) ignore exitValue={}, message={} - already called",
-                        this, exitValue, exitMessage);
+                log.trace("onExit({})[{}] ignore exitValue={}, message={} - already called",
+                    session, this, exitValue, exitMessage);
             }
             return;
         }
@@ -196,7 +206,8 @@ public abstract class AbstractCommandSupport
         ExitCallback cb = getExitCallback();
         try {
             if (log.isDebugEnabled()) {
-                log.debug("onExit({}) exiting - value={}, message={}", this, exitValue, exitMessage);
+                log.debug("onExit({})[{}] exiting - value={}, message={}",
+                    session, this, exitValue, exitMessage);
             }
             cb.onExit(exitValue, exitMessage);
         } finally {
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/kex/AbstractDHServerKeyExchange.java b/sshd-core/src/main/java/org/apache/sshd/server/kex/AbstractDHServerKeyExchange.java
index 7c11ec5..c8a796e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/kex/AbstractDHServerKeyExchange.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/kex/AbstractDHServerKeyExchange.java
@@ -19,6 +19,7 @@
 
 package org.apache.sshd.server.kex;
 
+import java.security.KeyPair;
 import java.security.PublicKey;
 import java.util.Objects;
 
@@ -31,9 +32,12 @@ import org.apache.sshd.server.session.ServerSessionHolder;
 /**
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public abstract class AbstractDHServerKeyExchange extends AbstractDHKeyExchange implements ServerSessionHolder {
+public abstract class AbstractDHServerKeyExchange
+        extends AbstractDHKeyExchange
+        implements ServerSessionHolder {
     protected AbstractDHServerKeyExchange(Session s) {
-        super(ValidateUtils.checkInstanceOf(s, ServerSession.class, "Using a client side KeyExchange on a server: %s", s));
+        super(ValidateUtils.checkInstanceOf(s, ServerSession.class,
+            "Using a client side KeyExchange on a server: %s", s));
     }
 
     @Override
@@ -44,6 +48,8 @@ public abstract class AbstractDHServerKeyExchange extends AbstractDHKeyExchange
     @Override
     public PublicKey getServerKey() {
         ServerSession session = getServerSession();
-        return Objects.requireNonNull(session.getHostKey(), "No server key pair available").getPublic();
+        KeyPair kpHost = Objects.requireNonNull(
+            session.getHostKey(), "No server key pair available");
+        return kpHost.getPublic();
     }
 }
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/shell/InvertedShell.java b/sshd-core/src/main/java/org/apache/sshd/server/shell/InvertedShell.java
index 0377afa..ade5e69 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/shell/InvertedShell.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/shell/InvertedShell.java
@@ -21,9 +21,12 @@ package org.apache.sshd.server.shell;
 import java.io.InputStream;
 import java.io.OutputStream;
 
+import org.apache.sshd.common.session.SessionHolder;
 import org.apache.sshd.server.SessionAware;
 import org.apache.sshd.server.channel.ChannelSession;
 import org.apache.sshd.server.command.CommandLifecycle;
+import org.apache.sshd.server.session.ServerSession;
+import org.apache.sshd.server.session.ServerSessionHolder;
 
 /**
  * This shell have inverted streams, such as the one obtained when launching a
@@ -33,7 +36,17 @@ import org.apache.sshd.server.command.CommandLifecycle;
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public interface InvertedShell extends CommandLifecycle, SessionAware {
+public interface InvertedShell
+        extends SessionHolder<ServerSession>,
+        ServerSessionHolder,
+        CommandLifecycle,
+        SessionAware {
+
+    @Override
+    default ServerSession getSession() {
+        return getServerSession();
+    }
+
     /**
      * @return The {@link ChannelSession} instance through which
      * the shell was created - may be {@code null} if shell not started yet
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/shell/ProcessShell.java b/sshd-core/src/main/java/org/apache/sshd/server/shell/ProcessShell.java
index a86eeb8..6b62cc1 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/shell/ProcessShell.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/shell/ProcessShell.java
@@ -38,14 +38,13 @@ import org.apache.sshd.server.Environment;
 import org.apache.sshd.server.channel.ChannelSession;
 import org.apache.sshd.server.channel.PuttyRequestHandler;
 import org.apache.sshd.server.session.ServerSession;
-import org.apache.sshd.server.session.ServerSessionHolder;
 
 /**
  * Bridges the I/O streams between the SSH command and the process that executes it
  *
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public class ProcessShell extends AbstractLoggingBean implements InvertedShell, ServerSessionHolder {
+public class ProcessShell extends AbstractLoggingBean implements InvertedShell {
     private final List<String> command;
     private String cmdValue;
     private ServerSession session;
@@ -65,7 +64,8 @@ public class ProcessShell extends AbstractLoggingBean implements InvertedShell,
 
     public ProcessShell(Collection<String> command) {
         // we copy the original list so as not to change it
-        this.command = new ArrayList<>(ValidateUtils.checkNotNullAndNotEmpty(command, "No process shell command(s)"));
+        this.command = new ArrayList<>(
+            ValidateUtils.checkNotNullAndNotEmpty(command, "No process shell command(s)"));
         this.cmdValue = GenericUtils.join(command, ' ');
     }
 
@@ -105,16 +105,17 @@ public class ProcessShell extends AbstractLoggingBean implements InvertedShell,
                 Map<String, String> procEnv = builder.environment();
                 procEnv.putAll(varsMap);
             } catch (Exception e) {
-                log.warn("start() - Failed ({}) to set environment for command={}: {}",
-                         e.getClass().getSimpleName(), cmdValue, e.getMessage());
+                log.warn("start({}) - Failed ({}) to set environment for command={}: {}",
+                     channel, e.getClass().getSimpleName(), cmdValue, e.getMessage());
                 if (log.isDebugEnabled()) {
-                    log.debug("start(" + cmdValue + ") failure details", e);
+                    log.debug("start(" + channel + ")[" + cmdValue + "] failure details", e);
                 }
             }
         }
 
         if (log.isDebugEnabled()) {
-            log.debug("Starting shell with command: '{}' and env: {}", builder.command(), builder.environment());
+            log.debug("start({}): command='{}', env={}",
+                channel, builder.command(), builder.environment());
         }
 
         process = builder.start();
@@ -177,7 +178,7 @@ public class ProcessShell extends AbstractLoggingBean implements InvertedShell,
         boolean debugEnabled = log.isDebugEnabled();
         if (process != null) {
             if (debugEnabled) {
-                log.debug("destroy({}) Destroy process for {}", channel, cmdValue);
+                log.debug("destroy({}) Destroy process for '{}'", channel, cmdValue);
             }
             process.destroy();
         }
@@ -186,14 +187,16 @@ public class ProcessShell extends AbstractLoggingBean implements InvertedShell,
             IoUtils.closeQuietly(getInputStream(), getOutputStream(), getErrorStream());
         if (e != null) {
             if (debugEnabled) {
-                log.debug(e.getClass().getSimpleName() + " while destroy streams of '" + this + "': " + e.getMessage());
+                log.debug("destroy({}) {} while destroy streams of '{}': {}",
+                    channel, e.getClass().getSimpleName(), this, e.getMessage());
             }
 
             if (log.isTraceEnabled()) {
                 Throwable[] suppressed = e.getSuppressed();
                 if (GenericUtils.length(suppressed) > 0) {
                     for (Throwable t : suppressed) {
-                        log.trace("Suppressed " + t.getClass().getSimpleName() + ") while destroy streams of '" + this + "': " + t.getMessage());
+                        log.trace("destroy({}) Suppressed {} while destroy streams of '{}': {}",
+                            channel, t.getClass().getSimpleName(), this, t.getMessage());
                     }
                 }
             }
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java b/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java
index 7e6aaac..fca8c99 100644
--- a/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java
@@ -79,14 +79,20 @@ public class InvertedShellWrapperTest extends BaseTestSupport {
 
     @Test   // see SSHD-570
     public void testExceptionWhilePumpStreams() throws Exception {
-        final BogusInvertedShell bogusShell = newShell("out", "err");
+        BogusInvertedShell bogusShell = newShell("out", "err");
         bogusShell.setAlive(false);
 
         final int destroyedExitValue = 7365;
+        @SuppressWarnings("checkstyle:anoninnerlength")
         InvertedShell shell = new InvertedShell() {
             private boolean destroyed;
 
             @Override
+            public ServerSession getServerSession() {
+                return bogusShell.getServerSession();
+            }
+
+            @Override
             public ChannelSession getChannelSession() {
                 return bogusShell.getChannelSession();
             }
@@ -188,7 +194,9 @@ public class InvertedShellWrapperTest extends BaseTestSupport {
              InputStream shellErr = newDelayedInputStream(Short.SIZE, errorContent);
              ByteArrayOutputStream stderr = new ByteArrayOutputStream(errorContent.length() + Byte.SIZE)) {
 
+            @SuppressWarnings("checkstyle:anoninnerlength")
             InvertedShell shell = new InvertedShell() {
+                private ServerSession session;
                 private ChannelSession channel;
 
                 @Override
@@ -197,13 +205,23 @@ public class InvertedShellWrapperTest extends BaseTestSupport {
                 }
 
                 @Override
+                public ServerSession getServerSession() {
+                    if (session != null) {
+                        return session;
+                    }
+
+                    ChannelSession channel = getChannelSession();
+                    return (channel == null) ? null : channel.getServerSession();
+                }
+
+                @Override
                 public ChannelSession getChannelSession() {
                     return channel;
                 }
 
                 @Override
                 public void setSession(ServerSession session) {
-                    // ignored
+                    this.session = session;
                 }
 
                 @Override
@@ -286,8 +304,10 @@ public class InvertedShellWrapperTest extends BaseTestSupport {
 
     private static BogusInvertedShell newShell(String contentOut, String contentErr) {
         ByteArrayOutputStream in = new ByteArrayOutputStream(20);
-        ByteArrayInputStream out = new ByteArrayInputStream(contentOut.getBytes(StandardCharsets.UTF_8));
-        ByteArrayInputStream err = new ByteArrayInputStream(contentErr.getBytes(StandardCharsets.UTF_8));
+        ByteArrayInputStream out =
+            new ByteArrayInputStream(contentOut.getBytes(StandardCharsets.UTF_8));
+        ByteArrayInputStream err =
+            new ByteArrayInputStream(contentErr.getBytes(StandardCharsets.UTF_8));
         return new BogusInvertedShell(in, out, err);
     }
 }
diff --git a/sshd-core/src/test/java/org/apache/sshd/util/test/BogusInvertedShell.java b/sshd-core/src/test/java/org/apache/sshd/util/test/BogusInvertedShell.java
index 6670529..ce5ccdc 100644
--- a/sshd-core/src/test/java/org/apache/sshd/util/test/BogusInvertedShell.java
+++ b/sshd-core/src/test/java/org/apache/sshd/util/test/BogusInvertedShell.java
@@ -28,11 +28,9 @@ import org.apache.sshd.common.util.io.IoUtils;
 import org.apache.sshd.server.Environment;
 import org.apache.sshd.server.channel.ChannelSession;
 import org.apache.sshd.server.session.ServerSession;
-import org.apache.sshd.server.session.ServerSessionHolder;
 import org.apache.sshd.server.shell.InvertedShell;
 
-public class BogusInvertedShell implements InvertedShell, ServerSessionHolder {
-
+public class BogusInvertedShell implements InvertedShell {
     private final OutputStream in;
     private final InputStream out;
     private final InputStream err;
diff --git a/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystemEnvironment.java b/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystemEnvironment.java
index a7a12b1..cebe9cf 100644
--- a/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystemEnvironment.java
+++ b/sshd-sftp/src/main/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystemEnvironment.java
@@ -23,14 +23,16 @@ import java.nio.file.Path;
 import java.util.stream.Collectors;
 import java.util.stream.IntStream;
 
+import org.apache.sshd.common.session.SessionHolder;
 import org.apache.sshd.common.subsystem.sftp.SftpConstants;
 import org.apache.sshd.server.config.SshServerConfigFileReader;
+import org.apache.sshd.server.session.ServerSession;
 import org.apache.sshd.server.session.ServerSessionHolder;
 
 /**
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
-public interface SftpSubsystemEnvironment extends ServerSessionHolder {
+public interface SftpSubsystemEnvironment extends SessionHolder<ServerSession>, ServerSessionHolder {
     /**
      * Force the use of a given sftp version
      */
@@ -44,6 +46,11 @@ public interface SftpSubsystemEnvironment extends ServerSessionHolder {
             .mapToObj(Integer::toString)
             .collect(Collectors.joining(","));
 
+    @Override
+    default ServerSession getSession() {
+        return getServerSession();
+    }
+
     /**
      * @return The negotiated version
      */


[mina-sshd] 04/07: [SSHD-842] Moved UserAuthMethodFactory from core to common module

Posted by lg...@apache.org.
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 a31a83ad0f22aa63f3f2c8afa6c1febb2cf86db8
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Oct 17 11:46:31 2019 +0300

    [SSHD-842] Moved UserAuthMethodFactory from core to common module
---
 .../src/main/java/org/apache/sshd/common/auth/UserAuthMethodFactory.java  | 0
 1 file changed, 0 insertions(+), 0 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/common/auth/UserAuthMethodFactory.java b/sshd-common/src/main/java/org/apache/sshd/common/auth/UserAuthMethodFactory.java
similarity index 100%
rename from sshd-core/src/main/java/org/apache/sshd/common/auth/UserAuthMethodFactory.java
rename to sshd-common/src/main/java/org/apache/sshd/common/auth/UserAuthMethodFactory.java


[mina-sshd] 05/07: [SSHD-842] Moved KexProposalOptionTest from core to common module

Posted by lg...@apache.org.
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 15b74e9eab394cb804e8bd9dbe4d40509c9c9380
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Thu Oct 17 11:58:48 2019 +0300

    [SSHD-842] Moved KexProposalOptionTest from core to common module
---
 .../apache/sshd/common/kex/KexProposalOptionTest.java   | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)

diff --git a/sshd-core/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java b/sshd-common/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java
similarity index 90%
rename from sshd-core/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java
rename to sshd-common/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java
index f6adc8d..4008dac 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java
+++ b/sshd-common/src/test/java/org/apache/sshd/common/kex/KexProposalOptionTest.java
@@ -26,7 +26,7 @@ import java.util.EnumSet;
 
 import org.apache.sshd.common.kex.KexProposalOption.Constants;
 import org.apache.sshd.common.util.GenericUtils;
-import org.apache.sshd.util.test.BaseTestSupport;
+import org.apache.sshd.util.test.JUnitTestSupport;
 import org.apache.sshd.util.test.NoIoTestCase;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
@@ -38,18 +38,21 @@ import org.junit.runners.MethodSorters;
  */
 @FixMethodOrder(MethodSorters.NAME_ASCENDING)
 @Category({ NoIoTestCase.class })
-public class KexProposalOptionTest extends BaseTestSupport {
+public class KexProposalOptionTest extends JUnitTestSupport {
     public KexProposalOptionTest() {
         super();
     }
 
     @Test
-    public void testFromName() {
+    public void testFromUnmatchedName() {
         for (String n : new String[]{null, "", getCurrentTestName()}) {
             KexProposalOption o = KexProposalOption.fromName(n);
             assertNull("Unexpected value for name='" + n + "'", o);
         }
+    }
 
+    @Test
+    public void testFromMatchedName() {
         for (KexProposalOption expected : KexProposalOption.VALUES) {
             String n = expected.name();
 
@@ -62,12 +65,15 @@ public class KexProposalOptionTest extends BaseTestSupport {
     }
 
     @Test
-    public void testFromProposalIndex() {
+    public void testFromUnmatchedProposalIndex() {
         for (int index : new int[]{-1, KexProposalOption.VALUES.size()}) {
             KexProposalOption o = KexProposalOption.fromProposalIndex(index);
             assertNull("Unexpected value for index=" + index, o);
         }
+    }
 
+    @Test
+    public void testFromMatchedProposalIndex() {
         for (KexProposalOption expected : KexProposalOption.VALUES) {
             int index = expected.getProposalIndex();
             KexProposalOption actual = KexProposalOption.fromProposalIndex(index);
@@ -95,7 +101,8 @@ public class KexProposalOptionTest extends BaseTestSupport {
     public void testAllConstantsCovered() throws Exception {
         Field[] fields = Constants.class.getFields();
 
-        Collection<KexProposalOption> options = EnumSet.allOf(KexProposalOption.class);
+        Collection<KexProposalOption> options =
+            EnumSet.allOf(KexProposalOption.class);
         for (Field f : fields) {
             int mods = f.getModifiers();
             if (!Modifier.isStatic(mods)) {