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 2020/08/07 14:52:39 UTC

[mina-sshd] 01/04: [SSHD-1050] Fixed race condition in AuthFuture if exception caught before authentication started

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 b848f767cc132aa18ef42989ef979d6f7e7eb57e
Author: Lyor Goldstein <lg...@apache.org>
AuthorDate: Tue Aug 4 11:01:03 2020 +0300

    [SSHD-1050] Fixed race condition in AuthFuture if exception caught before authentication started
---
 CHANGES.md                                         |  1 +
 .../sshd/client/future/InitialAuthFuture.java      | 52 +++++++++++++++++++
 .../sshd/client/session/ClientSessionImpl.java     | 16 ++++--
 .../sshd/client/session/ClientSessionTest.java     | 59 +++++++++++++++++++---
 4 files changed, 119 insertions(+), 9 deletions(-)

diff --git a/CHANGES.md b/CHANGES.md
index 089fa2b..0dbba59 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -38,3 +38,4 @@ or `-key-file` command line option.
 * [SSHD-1039](https://issues.apache.org/jira/browse/SSHD-1039) Fix support for some basic options in ssh/sshd cli.
 * [SSHD-1047](https://issues.apache.org/jira/browse/SSHD-1047) Support for SSH jumps.
 * [SSHD-1048](https://issues.apache.org/jira/browse/SSHD-1048) Wrap instead of rethrow IOException in Future.
+* [SSHD-1050](https://issues.apache.org/jira/browse/SSHD-1050) Fixed race condition in AuthFuture if exception caught before authentication started
\ No newline at end of file
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/future/InitialAuthFuture.java b/sshd-core/src/main/java/org/apache/sshd/client/future/InitialAuthFuture.java
new file mode 100644
index 0000000..375fdb4
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/client/future/InitialAuthFuture.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sshd.client.future;
+
+import org.apache.sshd.common.future.SshFutureListener;
+
+/**
+ * A special future used until the authentication service replaces it with a &quot;real&quot; one. This future serves as
+ * a placeholder for any exceptions caught until authentication starts. It is special in one other way - it has no
+ * listeners attached to it and expects no authentication success or failure - only exceptions.
+ *
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public class InitialAuthFuture extends DefaultAuthFuture {
+    public InitialAuthFuture(Object id, Object lock) {
+        super(id, lock);
+    }
+
+    @Override
+    public AuthFuture addListener(SshFutureListener<AuthFuture> listener) {
+        throw new UnsupportedOperationException("Not allowed to add listeners to this future");
+    }
+
+    @Override
+    protected void notifyListener(SshFutureListener<AuthFuture> l) {
+        if (l != null) {
+            throw new UnsupportedOperationException("No listeners expected for this future");
+        }
+    }
+
+    @Override
+    public void setAuthed(boolean authed) {
+        throw new UnsupportedOperationException("No authentication expected for this future");
+    }
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
index 21e0631..bc8a9bd 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/session/ClientSessionImpl.java
@@ -32,7 +32,7 @@ import java.util.concurrent.TimeUnit;
 
 import org.apache.sshd.client.ClientFactoryManager;
 import org.apache.sshd.client.future.AuthFuture;
-import org.apache.sshd.client.future.DefaultAuthFuture;
+import org.apache.sshd.client.future.InitialAuthFuture;
 import org.apache.sshd.common.Service;
 import org.apache.sshd.common.ServiceFactory;
 import org.apache.sshd.common.SshConstants;
@@ -85,8 +85,7 @@ public class ClientSessionImpl extends AbstractClientSession {
             nextServiceFactory = null;
         }
 
-        authFuture = new DefaultAuthFuture(ioSession.getRemoteAddress(), futureLock);
-        authFuture.setAuthed(false);
+        authFuture = new InitialAuthFuture(ioSession.getRemoteAddress(), futureLock);
 
         signalSessionCreated(ioSession);
 
@@ -124,8 +123,19 @@ public class ClientSessionImpl extends AbstractClientSession {
         ClientUserAuthService authService = getUserAuthService();
         synchronized (sessionLock) {
             String serviceName = nextServiceName();
+            // SSHD-1050 - check if need to propagate any previously caught exceptions
+            Throwable caught = (authFuture instanceof InitialAuthFuture) ? authFuture.getException() : null;
             authFuture = ValidateUtils.checkNotNull(
                     authService.auth(serviceName), "No auth future generated by service=%s", serviceName);
+            if (caught != null) {
+                /*
+                 * Safe to do under session lock despite SSHD-916 since
+                 * the newly generated future has no associated listeners
+                 * attached to it yet
+                 */
+                signalAuthFailure(authFuture, caught);
+            }
+
             return authFuture;
         }
     }
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionTest.java b/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionTest.java
index ed0addf..d9e022f 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionTest.java
@@ -26,15 +26,21 @@ import java.rmi.ServerException;
 import java.util.concurrent.atomic.AtomicInteger;
 
 import org.apache.sshd.client.SshClient;
+import org.apache.sshd.client.future.AuthFuture;
 import org.apache.sshd.common.AttributeRepository;
 import org.apache.sshd.common.AttributeRepository.AttributeKey;
 import org.apache.sshd.common.session.Session;
 import org.apache.sshd.common.session.SessionListener;
+import org.apache.sshd.core.CoreModuleProperties;
 import org.apache.sshd.server.SshServer;
+import org.apache.sshd.server.auth.keyboard.KeyboardInteractiveAuthenticator;
+import org.apache.sshd.server.auth.pubkey.AcceptAllPublickeyAuthenticator;
 import org.apache.sshd.util.test.BaseTestSupport;
+import org.apache.sshd.util.test.BogusPasswordAuthenticator;
 import org.apache.sshd.util.test.CommandExecutionHelper;
 import org.apache.sshd.util.test.CoreTestSupportUtils;
 import org.junit.AfterClass;
+import org.junit.Before;
 import org.junit.BeforeClass;
 import org.junit.FixMethodOrder;
 import org.junit.Test;
@@ -83,10 +89,17 @@ public class ClientSessionTest extends BaseTestSupport {
         }
     }
 
+    @Before
+    public void setUp() {
+        sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE);
+        sshd.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE);
+        sshd.setKeyboardInteractiveAuthenticator(KeyboardInteractiveAuthenticator.NONE);
+    }
+
     @Test
     public void testDefaultExecuteCommandMethod() throws Exception {
-        final String expectedCommand = getCurrentTestName() + "-CMD";
-        final String expectedResponse = getCurrentTestName() + "-RSP";
+        String expectedCommand = getCurrentTestName() + "-CMD";
+        String expectedResponse = getCurrentTestName() + "-RSP";
         sshd.setCommandFactory((session, command) -> new CommandExecutionHelper(command) {
             private boolean cmdProcessed;
 
@@ -116,8 +129,8 @@ public class ClientSessionTest extends BaseTestSupport {
 
     @Test
     public void testExceptionThrownIfRemoteStderrWrittenTo() throws Exception {
-        final String expectedCommand = getCurrentTestName() + "-CMD";
-        final String expectedErrorMessage = getCurrentTestName() + "-ERR";
+        String expectedCommand = getCurrentTestName() + "-CMD";
+        String expectedErrorMessage = getCurrentTestName() + "-ERR";
         sshd.setCommandFactory((session, command) -> new CommandExecutionHelper(command) {
             private boolean cmdProcessed;
 
@@ -161,8 +174,8 @@ public class ClientSessionTest extends BaseTestSupport {
 
     @Test
     public void testExceptionThrownIfNonZeroExitStatus() throws Exception {
-        final String expectedCommand = getCurrentTestName() + "-CMD";
-        final int expectedErrorCode = 7365;
+        String expectedCommand = getCurrentTestName() + "-CMD";
+        int expectedErrorCode = 7365;
         sshd.setCommandFactory((session, command) -> new CommandExecutionHelper(command) {
             private boolean cmdProcessed;
 
@@ -237,4 +250,38 @@ public class ClientSessionTest extends BaseTestSupport {
             client.removeSessionListener(listener);
         }
     }
+
+    @Test // SSHD-1050
+    public void testAuthGetsNotifiedOnLongPreamble() throws Exception {
+        int limit = CoreModuleProperties.MAX_IDENTIFICATION_SIZE.getRequired(sshd);
+        String line = getClass().getCanonicalName() + "#" + getCurrentTestName();
+        StringBuilder sb = new StringBuilder(limit + line.length());
+        while (sb.length() <= limit) {
+            if (sb.length() > 0) {
+                sb.append(CoreModuleProperties.SERVER_EXTRA_IDENT_LINES_SEPARATOR);
+            }
+            sb.append(line);
+        }
+        CoreModuleProperties.SERVER_EXTRA_IDENTIFICATION_LINES.set(sshd, sb.toString());
+
+        try (ClientSession session = client.connect(getCurrentTestName(), TEST_LOCALHOST, port)
+                .verify(CONNECT_TIMEOUT)
+                .getSession()) {
+            session.addPasswordIdentity(getCurrentTestName());
+            // Give time to the client to signal the overflow in server identification
+            Thread.sleep(AUTH_TIMEOUT.toMillis() / 2L);
+
+            AuthFuture future = session.auth();
+            assertTrue("Auth not completed on time", future.await(AUTH_TIMEOUT));
+            assertTrue("No auth result", future.isDone());
+            assertFalse("Unexpected auth success", future.isSuccess());
+            assertTrue("Auth not marked as failed", future.isFailure());
+
+            Throwable exception = future.getException();
+            String message = exception.getLocalizedMessage();
+            assertTrue("Invalid exception message: " + message, message.contains("too many header lines"));
+        } finally {
+            CoreModuleProperties.SERVER_EXTRA_IDENTIFICATION_LINES.set(sshd, null);
+        }
+    }
 }