You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by tw...@apache.org on 2026/09/26 14:46:29 UTC

(mina-sshd) branch rc-2.20.0 created (now 2221febd3)

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

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


      at 2221febd3 [maven-release-plugin] prepare release sshd-2.20.0

This branch includes the following new commits:

     new 758b100d7 Restrict async authentication
     new 4136358de ServerUserAuthService: ignore delayed async auth results
     new 530dbdb8e ServerUserAuthService: early return for unknown auth methods
     new 5d089237b Add a test for multi-authentication
     new 990e057e2 Multi-pubkey auth: enforce different keys on the server side
     new 7704e7efb Improve sanity checks in UserAuthKeyboardInteractive
     new b89e96270 sshd-git: also strip --output= and -o= arguments from archive
     new 588d4ee4f SCP: limit the protocol line length
     new 53bce94f4 DefaultSftpClient: simplify SFTP message handling
     new f4f562c29 Fix check-file-name/check-file-handle SFTP v6 extension
     new acc0f1ed4 Fix LDAP authentication
     new 53b57ceca Bump Bouncy Castle 1.85 -> 1.86
     new 602896f3e PublicKeyAuthenticator.authenticate(): remove AsyncAuthException
     new 1c97396ff Update CHANGES.md
     new cea7e2432 Bump BC-FIPS test dependencies
     new 0b41c6f95 Format PublickeyAuthenticator
     new daa400234 Prepare release documentation
     new 2221febd3 [maven-release-plugin] prepare release sshd-2.20.0

The 18 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.



(mina-sshd) 16/18: Format PublickeyAuthenticator

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 0b41c6f95caf8e29125d3202c37d2b1974ef14a8
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Sat Sep 26 13:22:16 2026 +0200

    Format PublickeyAuthenticator
---
 .../apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java    | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java b/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java
index 2ef3dfc37..dcdfa0ec3 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java
@@ -44,10 +44,10 @@ public interface PublickeyAuthenticator {
      * certificate authority, and that the given user name is listed in the certificate's principals.
      * </p>
      *
-     * @param  username           the username
-     * @param  key                the key
-     * @param  session            the server session
-     * @return                    {@code true} if the key may be used; {@code false} otherwise
+     * @param  username the username
+     * @param  key      the key
+     * @param  session  the server session
+     * @return          {@code true} if the key may be used; {@code false} otherwise
      */
     boolean authenticate(String username, PublicKey key, ServerSession session);
 


(mina-sshd) 15/18: Bump BC-FIPS test dependencies

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit cea7e243239467da206ad1deb0e3a4370c9e22e3
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Sat Sep 26 13:21:09 2026 +0200

    Bump BC-FIPS test dependencies
---
 sshd-core/pom.xml | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/sshd-core/pom.xml b/sshd-core/pom.xml
index fb72c3ce2..4905807f2 100644
--- a/sshd-core/pom.xml
+++ b/sshd-core/pom.xml
@@ -267,22 +267,22 @@
                                         <additionalClasspathDependency>
                                             <groupId>org.bouncycastle</groupId>
                                             <artifactId>bc-fips</artifactId>
-                                            <version>2.0.1</version>
+                                            <version>2.0.2</version>
                                         </additionalClasspathDependency>
                                         <additionalClasspathDependency>
                                             <groupId>org.bouncycastle</groupId>
                                             <artifactId>bcpkix-fips</artifactId>
-                                            <version>2.0.11</version>
+                                            <version>2.0.13</version>
                                         </additionalClasspathDependency>
                                         <additionalClasspathDependency>
                                             <groupId>org.bouncycastle</groupId>
                                             <artifactId>bcpg-fips</artifactId>
-                                            <version>2.0.12</version>
+                                            <version>2.0.14.1</version>
                                         </additionalClasspathDependency>
                                         <additionalClasspathDependency>
                                             <groupId>org.bouncycastle</groupId>
                                             <artifactId>bcutil-fips</artifactId>
-                                            <version>2.0.6</version>
+                                            <version>2.0.8</version>
                                         </additionalClasspathDependency>
                                     </additionalClasspathDependencies>
                                 </configuration>


(mina-sshd) 02/18: ServerUserAuthService: ignore delayed async auth results

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 4136358deceb7e830791e0329d0999703734147b
Author: Chris Jarrett-Davies <ch...@openai.com>
AuthorDate: Wed Sep 23 21:34:12 2026 +0200

    ServerUserAuthService: ignore delayed async auth results
    
    With asynchronous authentication it's possible that a new authentication
    request for a new method arrives before the asynchronous authentication
    completes. In such a case, the asynchronously computed authentication
    result is stale and must be discarded.
    
    Keep track of the current asynchronous execution, and if a new
    authentication request is received, clear the reference. When the
    asynchronous authentication is completed but is no longer current, its
    result is simply ignored.
---
 .../sshd/server/session/ServerUserAuthService.java |  25 +-
 .../auth/ServerUserAuthServiceAsyncTest.java       | 333 +++++++++++++++++++++
 2 files changed, 356 insertions(+), 2 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
index 53046183e..4e43e931f 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
@@ -78,6 +78,7 @@ public class ServerUserAuthService extends AbstractCloseable implements Service,
     private String authMethod;
     private String authService;
     private UserAuth currentAuth;
+    private AsyncAuthException pendingAuth;
 
     private int maxAuthRequests;
     private int nbAuthRequests;
@@ -156,6 +157,8 @@ public class ServerUserAuthService extends AbstractCloseable implements Service,
 
     @Override
     public synchronized void process(int cmd, Buffer buffer) throws Exception {
+        // A new request or continuation supersedes any pending result, even on the same authenticator.
+        pendingAuth = null;
         Boolean authed = Boolean.FALSE;
         ServerSession session = getServerSession();
         boolean debugEnabled = log.isDebugEnabled();
@@ -189,7 +192,7 @@ public class ServerUserAuthService extends AbstractCloseable implements Service,
             } catch (AsyncAuthException async) {
                 String authName = currentAuth.getName();
                 if (UserAuthPassword.NAME.equals(authName) || UserAuthKeyboardInteractive.NAME.equals(authName)) {
-                    async.addListener(authenticated -> asyncAuth(cmd, buffer, authenticated));
+                    addAsyncAuthListener(async, cmd, buffer);
                     return;
                 }
                 throw new IllegalStateException(
@@ -340,7 +343,7 @@ public class ServerUserAuthService extends AbstractCloseable implements Service,
         } catch (AsyncAuthException async) {
             String authName = currentAuth.getName();
             if (UserAuthPassword.NAME.equals(authName) || UserAuthKeyboardInteractive.NAME.equals(authName)) {
-                async.addListener(authenticated -> asyncAuth(SshConstants.SSH_MSG_USERAUTH_REQUEST, buffer, authenticated));
+                addAsyncAuthListener(async, SshConstants.SSH_MSG_USERAUTH_REQUEST, buffer);
                 return false;
             }
             throw new IllegalStateException(
@@ -353,6 +356,24 @@ public class ServerUserAuthService extends AbstractCloseable implements Service,
         return true;
     }
 
+    private void addAsyncAuthListener(AsyncAuthException async, int cmd, Buffer buffer) {
+        UserAuth auth = currentAuth;
+        pendingAuth = async;
+        async.addListener(authenticated -> {
+            synchronized (ServerUserAuthService.this) {
+                if (pendingAuth != async) {
+                    return;
+                }
+                pendingAuth = null;
+                ServerSession session = getServerSession();
+                if (currentAuth != auth || isClosing() || session.isClosing() || session.isAuthenticated()) {
+                    return;
+                }
+                asyncAuth(cmd, buffer, authenticated);
+            }
+        });
+    }
+
     protected synchronized void asyncAuth(int cmd, Buffer buffer, boolean authed) {
         try {
             if (authed) {
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/auth/ServerUserAuthServiceAsyncTest.java b/sshd-core/src/test/java/org/apache/sshd/server/auth/ServerUserAuthServiceAsyncTest.java
new file mode 100644
index 000000000..c7f10c6eb
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/server/auth/ServerUserAuthServiceAsyncTest.java
@@ -0,0 +1,333 @@
+/*
+ * 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.server.auth;
+
+import java.io.IOException;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.List;
+
+import org.apache.sshd.common.SshConstants;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
+import org.apache.sshd.server.session.ServerSession;
+import org.apache.sshd.server.session.ServerUserAuthService;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyByte;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests for password or keyboard-interactive asynchronous authentication.
+ */
+public class ServerUserAuthServiceAsyncTest {
+
+    @ParameterizedTest
+    @ValueSource(booleans = { true, false })
+    void replacedMethodDiscardsOldResult(boolean result) throws Exception {
+        AsyncAuthException old = new AsyncAuthException();
+        StepAuth password = new StepAuth("password", pending(old));
+        StepAuth publicKey = new StepAuth("publickey", () -> null);
+        Fixture f = new Fixture(factory(password), factory(publicKey));
+        f.request("password");
+        f.request("publickey");
+        old.setAuthed(result);
+        f.assertUnchanged(publicKey, 0);
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { true, false })
+    void replacedInstanceKeepsNewPendingResult(boolean result) throws Exception {
+        AsyncAuthException old = new AsyncAuthException();
+        AsyncAuthException current = new AsyncAuthException();
+        StepAuth first = new StepAuth("password", pending(old));
+        StepAuth second = new StepAuth("password", pending(current));
+        Fixture f = new Fixture(factory(first, second));
+        f.request("password");
+        f.request("password");
+        old.setAuthed(result);
+        f.assertUnchanged(second, 0);
+        current.setAuthed(true);
+        f.assertSuccess();
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { true, false })
+    void sameAuthenticatorContinuationKeepsNewPendingResult(boolean result) throws Exception {
+        AsyncAuthException old = new AsyncAuthException();
+        AsyncAuthException current = new AsyncAuthException();
+        StepAuth interactive = new StepAuth("keyboard-interactive", () -> null, pending(old), pending(current));
+        Fixture f = new Fixture(factory(interactive));
+        f.request("keyboard-interactive");
+        f.continuation();
+        f.continuation();
+        old.setAuthed(result);
+        f.assertUnchanged(interactive, 0);
+        current.setAuthed(true);
+        f.assertSuccess();
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { true, false })
+    void incompleteContinuationDiscardsOldResult(boolean result) throws Exception {
+        AsyncAuthException old = new AsyncAuthException();
+        StepAuth interactive = new StepAuth("keyboard-interactive", () -> null, pending(old), () -> null);
+        Fixture f = new Fixture(factory(interactive));
+        f.request("keyboard-interactive");
+        f.continuation();
+        f.continuation();
+        old.setAuthed(result);
+        f.assertUnchanged(interactive, 0);
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { true, false })
+    void destructionCannotCompleteSupersededRequest(boolean result) throws Exception {
+        AsyncAuthException old = new AsyncAuthException();
+        StepAuth password = new StepAuth("password", pending(old));
+        password.onDestroy = () -> old.setAuthed(result);
+        StepAuth publicKey = new StepAuth("publickey", () -> null);
+        Fixture f = new Fixture(factory(password), factory(publicKey));
+        f.request("password");
+        f.request("publickey");
+        f.assertUnchanged(publicKey, 0);
+        assertEquals(1, password.destroyed);
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { true, false })
+    void alreadyCompletedResultIsDelivered(boolean result) throws Exception {
+        AsyncAuthException completed = new AsyncAuthException();
+        completed.setAuthed(result);
+        StepAuth password = new StepAuth("password", pending(completed));
+        Fixture f = new Fixture(factory(password));
+        f.request("password");
+        assertEquals(1, f.service.completions);
+        assertEquals(1, password.destroyed);
+        if (result) {
+            f.assertSuccess();
+        } else {
+            verify(f.session, never()).signalAuthenticationSuccess(anyString(), anyString(), any());
+            assertEquals(1, f.packets.size());
+            assertEquals(SshConstants.SSH_MSG_USERAUTH_FAILURE, f.packets.get(0).getByte());
+        }
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { true, false })
+    void serviceClosureDiscardsResult(boolean result) throws Exception {
+        AsyncAuthException pending = new AsyncAuthException();
+        StepAuth password = new StepAuth("password", pending(pending));
+        Fixture f = new Fixture(factory(password));
+        f.request("password");
+        f.service.close(true);
+        pending.setAuthed(result);
+        f.assertUnchanged(password, 0);
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { true, false })
+    void sessionClosureDiscardsResult(boolean result) throws Exception {
+        AsyncAuthException pending = new AsyncAuthException();
+        StepAuth password = new StepAuth("password", pending(pending));
+        Fixture f = new Fixture(factory(password));
+        f.request("password");
+        when(f.session.isClosing()).thenReturn(true);
+        pending.setAuthed(result);
+        f.assertUnchanged(password, 0);
+    }
+
+    @ParameterizedTest
+    @ValueSource(booleans = { true, false })
+    void authenticatedSessionDiscardsResult(boolean result) throws Exception {
+        AsyncAuthException pending = new AsyncAuthException();
+        StepAuth password = new StepAuth("password", pending(pending));
+        Fixture f = new Fixture(factory(password));
+        f.request("password");
+        when(f.session.isAuthenticated()).thenReturn(true);
+        pending.setAuthed(result);
+        f.assertUnchanged(password, 0);
+    }
+
+    @Test
+    void unsupportedRequestInvalidatesPendingResult() throws Exception {
+        AsyncAuthException old = new AsyncAuthException();
+        StepAuth password = new StepAuth("password", pending(old));
+        Fixture f = new Fixture(factory(password));
+        f.request("password");
+        f.request("unsupported");
+        old.setAuthed(true);
+        assertEquals(1, f.packets.size());
+        assertEquals(0, f.service.completions);
+        verify(f.session, never()).signalAuthenticationSuccess(anyString(), anyString(), any());
+    }
+
+    @Test
+    void malformedRequestInvalidatesPendingResult() throws Exception {
+        AsyncAuthException old = new AsyncAuthException();
+        StepAuth password = new StepAuth("password", pending(old));
+        Fixture f = new Fixture(factory(password));
+        f.request("password");
+        assertThrows(RuntimeException.class,
+                () -> f.service.process(SshConstants.SSH_MSG_USERAUTH_REQUEST, new ByteArrayBuffer()));
+        old.setAuthed(true);
+        assertEquals(0, f.service.completions);
+        verify(f.session, never()).signalAuthenticationSuccess(anyString(), anyString(), any());
+    }
+
+    @Test
+    void legitimateMethodSwitchCanComplete() throws Exception {
+        AsyncAuthException old = new AsyncAuthException();
+        StepAuth password = new StepAuth("password", pending(old));
+        StepAuth publicKey = new StepAuth("publickey", () -> true);
+        Fixture f = new Fixture(factory(password), factory(publicKey));
+        f.request("password");
+        f.request("publickey");
+        old.setAuthed(false);
+        verify(f.session).signalAuthenticationSuccess(anyString(), anyString(), any());
+        assertEquals(0, f.service.completions);
+        assertEquals(0, f.packets.size());
+        assertEquals(1, publicKey.destroyed);
+    }
+
+    private static AuthStep pending(AsyncAuthException exception) {
+        return () -> {
+            throw exception;
+        };
+    }
+
+    private static UserAuthFactory factory(StepAuth... authenticators) {
+        Deque<StepAuth> remaining = new ArrayDeque<>(Arrays.asList(authenticators));
+        return new UserAuthFactory() {
+            @Override
+            public String getName() {
+                return authenticators[0].getName();
+            }
+
+            @Override
+            public UserAuth createUserAuth(ServerSession session) {
+                return remaining.removeFirst();
+            }
+        };
+    }
+
+    @FunctionalInterface
+    private interface AuthStep {
+        Boolean authenticate();
+    }
+
+    private static class StepAuth extends AbstractUserAuth {
+        private final Deque<AuthStep> steps;
+        private int destroyed;
+        private Runnable onDestroy = () -> {
+        };
+
+        StepAuth(String method, AuthStep... steps) {
+            super(method);
+            this.steps = new ArrayDeque<>(Arrays.asList(steps));
+        }
+
+        @Override
+        protected Boolean doAuth(Buffer buffer, boolean init) {
+            return steps.removeFirst().authenticate();
+        }
+
+        @Override
+        public void destroy() {
+            destroyed++;
+            onDestroy.run();
+        }
+    }
+
+    private static class TrackingService extends ServerUserAuthService {
+        private int completions;
+
+        TrackingService(ServerSession session) throws IOException {
+            super(session);
+        }
+
+        @Override
+        protected synchronized void asyncAuth(int cmd, Buffer buffer, boolean authed) {
+            completions++;
+            super.asyncAuth(cmd, buffer, authed);
+        }
+    }
+
+    private static class Fixture {
+        private final ServerSession session = mock(ServerSession.class);
+        private final List<Buffer> packets = new ArrayList<>();
+        private final TrackingService service;
+
+        Fixture(UserAuthFactory... factories) throws Exception {
+            when(session.getProperties()).thenReturn(new HashMap<>());
+            when(session.getUserAuthFactories()).thenReturn(Arrays.asList(factories));
+            when(session.createBuffer(anyByte(), anyInt())).thenAnswer(invocation -> {
+                Buffer buffer = new ByteArrayBuffer();
+                buffer.putByte(invocation.getArgument(0));
+                return buffer;
+            });
+            when(session.writePacket(any(Buffer.class))).thenAnswer(invocation -> {
+                packets.add(invocation.getArgument(0));
+                return null;
+            });
+            service = new TrackingService(session);
+        }
+
+        void request(String method) throws Exception {
+            Buffer buffer = new ByteArrayBuffer();
+            buffer.putString("alice");
+            buffer.putString("ssh-connection");
+            buffer.putString(method);
+            service.process(SshConstants.SSH_MSG_USERAUTH_REQUEST, buffer);
+        }
+
+        void continuation() throws Exception {
+            Buffer buffer = new ByteArrayBuffer();
+            buffer.putByte(SshConstants.SSH_MSG_USERAUTH_INFO_RESPONSE);
+            buffer.rpos(1);
+            service.process(SshConstants.SSH_MSG_USERAUTH_INFO_RESPONSE, buffer);
+        }
+
+        void assertUnchanged(StepAuth current, int expectedPackets) throws Exception {
+            assertEquals(0, service.completions);
+            assertEquals(0, current.destroyed);
+            assertEquals(expectedPackets, packets.size());
+            verify(session, never()).signalAuthenticationSuccess(anyString(), anyString(), any());
+        }
+
+        void assertSuccess() throws Exception {
+            assertEquals(1, service.completions);
+            verify(session).signalAuthenticationSuccess(anyString(), anyString(), any());
+            assertEquals(0, packets.size());
+        }
+    }
+}


(mina-sshd) 01/18: Restrict async authentication

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 758b100d74e7f6ee5055edc3058bbf9edba1de24
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Thu Aug 20 21:35:49 2026 +0200

    Restrict async authentication
    
    Allow it only for password or keyboard-interactive authentication. For
    other authentication schemes, the current design won't work.
---
 .../sshd/server/session/ServerUserAuthService.java | 20 +++++++--
 .../common/auth/PublicKeyAuthenticationTest.java   | 48 ++++++++++++++++++++++
 2 files changed, 64 insertions(+), 4 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
index de51b0a77..53046183e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
@@ -40,6 +40,8 @@ import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
 import java.util.stream.Collectors;
 
+import org.apache.sshd.client.auth.keyboard.UserAuthKeyboardInteractive;
+import org.apache.sshd.client.auth.password.UserAuthPassword;
 import org.apache.sshd.common.NamedResource;
 import org.apache.sshd.common.Service;
 import org.apache.sshd.common.SshConstants;
@@ -185,8 +187,13 @@ public class ServerUserAuthService extends AbstractCloseable implements Service,
             try {
                 authed = currentAuth.next(buffer);
             } catch (AsyncAuthException async) {
-                async.addListener(authenticated -> asyncAuth(cmd, buffer, authenticated));
-                return;
+                String authName = currentAuth.getName();
+                if (UserAuthPassword.NAME.equals(authName) || UserAuthKeyboardInteractive.NAME.equals(authName)) {
+                    async.addListener(authenticated -> asyncAuth(cmd, buffer, authenticated));
+                    return;
+                }
+                throw new IllegalStateException(
+                        "Async authentication only allowed for password or keyboard-interactive authentication", async);
             } catch (Exception e) {
                 // Continue
                 warn("process({}) Failed ({}) to authenticate using current method={}: {}",
@@ -331,8 +338,13 @@ public class ServerUserAuthService extends AbstractCloseable implements Service,
             Boolean authed = currentAuth.auth(session, username, service, buffer);
             authHolder.set(authed);
         } catch (AsyncAuthException async) {
-            async.addListener(authenticated -> asyncAuth(SshConstants.SSH_MSG_USERAUTH_REQUEST, buffer, authenticated));
-            return false;
+            String authName = currentAuth.getName();
+            if (UserAuthPassword.NAME.equals(authName) || UserAuthKeyboardInteractive.NAME.equals(authName)) {
+                async.addListener(authenticated -> asyncAuth(SshConstants.SSH_MSG_USERAUTH_REQUEST, buffer, authenticated));
+                return false;
+            }
+            throw new IllegalStateException(
+                    "Async authentication only allowed for password or keyboard-interactive authentication", async);
         } catch (Exception e) {
             warn("handleUserAuthRequestMessage({}) Failed ({}) to authenticate using factory method={}: {}",
                     session, e.getClass().getSimpleName(), method, e.getMessage(), e);
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/auth/PublicKeyAuthenticationTest.java b/sshd-core/src/test/java/org/apache/sshd/common/auth/PublicKeyAuthenticationTest.java
index 7d8a2db04..47b0a02c6 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/auth/PublicKeyAuthenticationTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/auth/PublicKeyAuthenticationTest.java
@@ -24,6 +24,7 @@ import java.io.InputStream;
 import java.net.URL;
 import java.security.GeneralSecurityException;
 import java.security.KeyPair;
+import java.security.PrivateKey;
 import java.security.PublicKey;
 import java.security.spec.InvalidKeySpecException;
 import java.util.ArrayList;
@@ -32,8 +33,11 @@ import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicReference;
 import java.util.stream.Stream;
 
 import org.apache.sshd.certificate.OpenSshCertificateBuilder;
@@ -60,6 +64,7 @@ import org.apache.sshd.common.util.ValidateUtils;
 import org.apache.sshd.common.util.buffer.Buffer;
 import org.apache.sshd.common.util.io.resource.URLResource;
 import org.apache.sshd.common.util.security.SecurityUtils;
+import org.apache.sshd.server.auth.AsyncAuthException;
 import org.apache.sshd.server.auth.keyboard.KeyboardInteractiveAuthenticator;
 import org.apache.sshd.server.auth.password.RejectAllPasswordAuthenticator;
 import org.apache.sshd.server.auth.pubkey.RejectAllPublickeyAuthenticator;
@@ -422,6 +427,49 @@ public class PublicKeyAuthenticationTest extends AuthenticationTestSupport {
         assertEquals(4 /* 3 attempts + null */, attemptsCount.getAndSet(0), "Mismatched retries count");
     }
 
+    @Test
+    void testAsyncAuth() throws Exception {
+        KeyPair clientIdentity = CommonTestSupportUtils.generateKeyPair(KeyUtils.EC_ALGORITHM, 256);
+        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
+        try {
+            sshd.setPublickeyAuthenticator((username, key, session) -> {
+                AsyncAuthException async = new AsyncAuthException();
+                scheduler.schedule(() -> async.setAuthed(KeyUtils.compareKeys(clientIdentity.getPublic(), key)), 100,
+                        TimeUnit.MILLISECONDS);
+                throw async;
+            });
+            try (SshClient client = setupTestClient()) {
+                client.start();
+                AtomicReference<PrivateKey> signingKey = new AtomicReference<>();
+                PublicKeyAuthenticationReporter reporter = new PublicKeyAuthenticationReporter() {
+                    @Override
+                    public void signalSignatureAttempt(
+                            ClientSession session, String service, KeyPair identity,
+                            String signature, byte[] signed) throws Exception {
+                        signingKey.set(identity.getPrivate());
+                    }
+                };
+                ClientSession s = client.connect(getCurrentTestName(), TEST_LOCALHOST, port).verify(CONNECT_TIMEOUT)
+                        .getSession();
+                try {
+                    s.addPublicKeyIdentity(clientIdentity);
+                    s.setPublicKeyAuthenticationReporter(reporter);
+                    s.auth().verify(AUTH_TIMEOUT);
+                    assertTrue(KeyUtils.compareKeys(clientIdentity.getPrivate(), signingKey.get()));
+                } catch (SshException e) {
+                    assertFalse(s.isOpen());
+                } finally {
+                    if (s.isOpen()) {
+                        s.close();
+                    }
+                    client.stop();
+                }
+            }
+        } finally {
+            scheduler.shutdownNow();
+        }
+    }
+
     @Test
     void rsaAuthenticationOldServer() throws Exception {
         KeyPair userkey = CommonTestSupportUtils.generateKeyPair(KeyUtils.RSA_ALGORITHM, 2048);


(mina-sshd) 18/18: [maven-release-plugin] prepare release sshd-2.20.0

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 2221febd396cd3daafdfbf2ff982c6d0eb69a203
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Sat Sep 26 14:42:36 2026 +0200

    [maven-release-plugin] prepare release sshd-2.20.0
---
 assembly/pom.xml         | 2 +-
 pom.xml                  | 6 +++---
 sshd-benchmarks/pom.xml  | 2 +-
 sshd-cli/pom.xml         | 2 +-
 sshd-common/pom.xml      | 2 +-
 sshd-contrib/pom.xml     | 2 +-
 sshd-core/pom.xml        | 2 +-
 sshd-git/pom.xml         | 2 +-
 sshd-ldap/pom.xml        | 2 +-
 sshd-mina/pom.xml        | 2 +-
 sshd-netty/pom.xml       | 2 +-
 sshd-openpgp/pom.xml     | 2 +-
 sshd-osgi/pom.xml        | 2 +-
 sshd-putty/pom.xml       | 2 +-
 sshd-scp/pom.xml         | 2 +-
 sshd-sftp/pom.xml        | 2 +-
 sshd-spring-sftp/pom.xml | 2 +-
 17 files changed, 19 insertions(+), 19 deletions(-)

diff --git a/assembly/pom.xml b/assembly/pom.xml
index bb800bc1a..34d559975 100644
--- a/assembly/pom.xml
+++ b/assembly/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
     </parent>
 
     <artifactId>apache-sshd</artifactId>
diff --git a/pom.xml b/pom.xml
index 135b933c0..da5005dce 100644
--- a/pom.xml
+++ b/pom.xml
@@ -27,7 +27,7 @@
 
     <groupId>org.apache.sshd</groupId>
     <artifactId>sshd</artifactId>
-    <version>2.20.0-SNAPSHOT</version>
+    <version>2.20.0</version>
     <name>Apache Mina SSHD</name>
     <packaging>pom</packaging>
     <inceptionYear>2008</inceptionYear>
@@ -67,7 +67,7 @@
         <connection>scm:git:https://gitbox.apache.org/repos/asf/mina-sshd.git</connection>
         <developerConnection>scm:git:https://gitbox.apache.org/repos/asf/mina-sshd.git</developerConnection>
         <url>https://github.com/apache/mina-sshd/tree/${project.scm.tag}</url>
-        <tag>master</tag>
+        <tag>sshd-2.20.0</tag>
     </scm>
 
     <properties>
@@ -80,7 +80,7 @@
 
 
         <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
-        <project.build.outputTimestamp>2026-06-30T21:47:32Z</project.build.outputTimestamp>
+        <project.build.outputTimestamp>2026-09-26T12:39:28Z</project.build.outputTimestamp>
 
         <java.sdk.version>8</java.sdk.version>
         <javac.source>${java.sdk.version}</javac.source>
diff --git a/sshd-benchmarks/pom.xml b/sshd-benchmarks/pom.xml
index 7fce5076d..1bb02fda6 100644
--- a/sshd-benchmarks/pom.xml
+++ b/sshd-benchmarks/pom.xml
@@ -20,7 +20,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
         <relativePath>..</relativePath>
     </parent>
 
diff --git a/sshd-cli/pom.xml b/sshd-cli/pom.xml
index eb8a744b5..a0ac804ec 100644
--- a/sshd-cli/pom.xml
+++ b/sshd-cli/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
     </parent>
 
     <artifactId>sshd-cli</artifactId>
diff --git a/sshd-common/pom.xml b/sshd-common/pom.xml
index a69c965fc..ac016b992 100644
--- a/sshd-common/pom.xml
+++ b/sshd-common/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
         <relativePath>..</relativePath>
     </parent>
 
diff --git a/sshd-contrib/pom.xml b/sshd-contrib/pom.xml
index 3df87473a..822d4454b 100644
--- a/sshd-contrib/pom.xml
+++ b/sshd-contrib/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
     </parent>
 
     <!-- NOTE ::: NOTE ::: NOTE ::: NOTE ::: NOTE ::: NOTE ::: NOTE ::: NOTE :::
diff --git a/sshd-core/pom.xml b/sshd-core/pom.xml
index 4905807f2..85e65d65b 100644
--- a/sshd-core/pom.xml
+++ b/sshd-core/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
         <relativePath>..</relativePath>
     </parent>
 
diff --git a/sshd-git/pom.xml b/sshd-git/pom.xml
index a0d376b3d..3f5ff5db4 100644
--- a/sshd-git/pom.xml
+++ b/sshd-git/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
     </parent>
 
     <artifactId>sshd-git</artifactId>
diff --git a/sshd-ldap/pom.xml b/sshd-ldap/pom.xml
index 7ef2d9167..b65248fc7 100644
--- a/sshd-ldap/pom.xml
+++ b/sshd-ldap/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
     </parent>
 
     <artifactId>sshd-ldap</artifactId>
diff --git a/sshd-mina/pom.xml b/sshd-mina/pom.xml
index b2fb40ed6..a2f63a0e5 100644
--- a/sshd-mina/pom.xml
+++ b/sshd-mina/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
         <relativePath>..</relativePath>
     </parent>
 
diff --git a/sshd-netty/pom.xml b/sshd-netty/pom.xml
index 875759c27..c0b6dad54 100644
--- a/sshd-netty/pom.xml
+++ b/sshd-netty/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
         <relativePath>..</relativePath>
     </parent>
 
diff --git a/sshd-openpgp/pom.xml b/sshd-openpgp/pom.xml
index 1966b0915..d4fce709d 100644
--- a/sshd-openpgp/pom.xml
+++ b/sshd-openpgp/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
         <relativePath>..</relativePath>
     </parent>
 
diff --git a/sshd-osgi/pom.xml b/sshd-osgi/pom.xml
index 8efe301e5..9ba9d9d91 100644
--- a/sshd-osgi/pom.xml
+++ b/sshd-osgi/pom.xml
@@ -24,7 +24,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
     </parent>
 
     <artifactId>sshd-osgi</artifactId>
diff --git a/sshd-putty/pom.xml b/sshd-putty/pom.xml
index c5459bbd0..0d6c84f3a 100644
--- a/sshd-putty/pom.xml
+++ b/sshd-putty/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
         <relativePath>..</relativePath>
     </parent>
 
diff --git a/sshd-scp/pom.xml b/sshd-scp/pom.xml
index b6945a145..b866b8543 100644
--- a/sshd-scp/pom.xml
+++ b/sshd-scp/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
     </parent>
 
     <artifactId>sshd-scp</artifactId>
diff --git a/sshd-sftp/pom.xml b/sshd-sftp/pom.xml
index bf39198bf..bee296d21 100644
--- a/sshd-sftp/pom.xml
+++ b/sshd-sftp/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
     </parent>
 
     <artifactId>sshd-sftp</artifactId>
diff --git a/sshd-spring-sftp/pom.xml b/sshd-spring-sftp/pom.xml
index 95aa1e720..f3771e9d6 100644
--- a/sshd-spring-sftp/pom.xml
+++ b/sshd-spring-sftp/pom.xml
@@ -22,7 +22,7 @@
     <parent>
         <groupId>org.apache.sshd</groupId>
         <artifactId>sshd</artifactId>
-        <version>2.20.0-SNAPSHOT</version>
+        <version>2.20.0</version>
     </parent>
 
     <artifactId>sshd-spring-sftp</artifactId>


(mina-sshd) 03/18: ServerUserAuthService: early return for unknown auth methods

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 530dbdb8ef5de803e84adbb554cad1826640a1be
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Wed Sep 23 23:52:57 2026 +0200

    ServerUserAuthService: early return for unknown auth methods
    
    Return SSH_MSG_USERAUTH_FAILURE early
    
    - for unknown authentication methods or
    - for methods not in the advertised set of methods that can continue.
    
    Previous code would in the second case run the authentication method,
    but then always return a failure. Returning an early failure avoids
    even running the method.
---
 .../org/apache/sshd/server/session/ServerUserAuthService.java     | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
index 4e43e931f..b9bac54dc 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/session/ServerUserAuthService.java
@@ -317,7 +317,13 @@ public class ServerUserAuthService extends AbstractCloseable implements Service,
             return false;
         }
 
-        // TODO: verify that the service is supported
+        if ("none".equals(method)) {
+            return true;
+        } else if (!authMethods.stream().filter(GenericUtils::isNotEmpty).map(l -> l.get(0)).anyMatch(s -> method.equals(s))) {
+            log.warn("handleUserAuthRequestMessage({}) client sent method={} not in methods that can proceed {}", session,
+                    method, authMethods);
+            return true;
+        }
         this.authMethod = method;
         if (debugEnabled) {
             log.debug(


(mina-sshd) 12/18: Bump Bouncy Castle 1.85 -> 1.86

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 53b57cecaac5486cbfd4f5723da0e71bf21116cc
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Thu Sep 24 21:56:17 2026 +0200

    Bump Bouncy Castle 1.85 -> 1.86
---
 pom.xml | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/pom.xml b/pom.xml
index 989de4ca2..135b933c0 100644
--- a/pom.xml
+++ b/pom.xml
@@ -97,7 +97,7 @@
         <ant.build.javac.target>${javac.target}</ant.build.javac.target>
 
         <groovy.version>4.0.17</groovy.version>
-        <bouncycastle.version>1.85</bouncycastle.version>
+        <bouncycastle.version>1.86</bouncycastle.version>
             <!-- NOTE: upgrading slf4j beyond this version causes
 
             Execution verify-style of goal org.apache.maven.plugins:maven-checkstyle-plugin:3.1.2:check failed.: NullPointerException


(mina-sshd) 05/18: Multi-pubkey auth: enforce different keys on the server side

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 990e057e26dc602e9887e2df53bc87c7b316a571
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Thu Sep 17 23:54:33 2026 +0200

    Multi-pubkey auth: enforce different keys on the server side
    
    A "publickey,publickey" authentication policy must not be satisfied by
    presenting the same key twice. Remember authenticated keys in an
    attribute on the SSH ServerSession. Refuse to authenticate a key
    multiple times.
---
 .../sshd/server/auth/pubkey/UserAuthPublicKey.java |  25 +++++
 .../server/auth/CertificateReuseMultiAuthTest.java | 112 +++++++++++++++++++
 .../sshd/server/auth/PublicKeyMultiAuthTest.java   | 124 +++++++++++++++++++++
 3 files changed, 261 insertions(+)

diff --git a/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/UserAuthPublicKey.java b/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/UserAuthPublicKey.java
index 9b4b4b40d..18cd5990b 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/UserAuthPublicKey.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/UserAuthPublicKey.java
@@ -24,10 +24,12 @@ import java.net.SocketAddress;
 import java.security.PublicKey;
 import java.security.SignatureException;
 import java.security.cert.CertificateException;
+import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
 import java.util.Map;
 
+import org.apache.sshd.common.AttributeRepository;
 import org.apache.sshd.common.NamedFactory;
 import org.apache.sshd.common.NamedResource;
 import org.apache.sshd.common.RuntimeSshException;
@@ -56,6 +58,9 @@ import org.apache.sshd.server.session.ServerSession;
 public class UserAuthPublicKey extends AbstractUserAuth implements SignatureFactoriesManager {
     public static final String NAME = UserAuthPublicKeyFactory.NAME;
 
+    public static final AttributeRepository.AttributeKey<List<PublicKey>> AUTHENTICATED_KEYS
+            = new AttributeRepository.AttributeKey<>();
+
     private List<NamedFactory<Signature>> factories;
 
     public UserAuthPublicKey() {
@@ -99,6 +104,7 @@ public class UserAuthPublicKey extends AbstractUserAuth implements SignatureFact
         buffer.wpos(buffer.rpos() + len);
 
         PublicKey key = buffer.getRawPublicKey();
+
         PublicKey verifyKey = key;
 
         if (key instanceof OpenSshCertificate) {
@@ -121,6 +127,11 @@ public class UserAuthPublicKey extends AbstractUserAuth implements SignatureFact
             verifyKey = cert.getCertPubKey();
         }
 
+        List<PublicKey> previouslyAuthenticatedKeys = session.getAttribute(AUTHENTICATED_KEYS);
+        if (alreadyAuthenticated(verifyKey, previouslyAuthenticatedKeys)) {
+            return Boolean.FALSE;
+        }
+
         Collection<NamedFactory<Signature>> factories = ValidateUtils.checkNotNullAndNotEmpty(
                 SignatureFactoriesManager.resolveSignatureFactories(this, session),
                 "No signature factories for session=%s",
@@ -173,6 +184,7 @@ public class UserAuthPublicKey extends AbstractUserAuth implements SignatureFact
             return null;
         }
 
+        PublicKey presentedKey = verifyKey;
         if (verifyKey instanceof SecurityKeyPublicKey<?>) {
             AuthorizedKeyEntry entry = session.getAttribute(AuthorizedKeyEntriesPublickeyAuthenticator.AUTHORIZED_KEY);
             if (entry != null) {
@@ -188,6 +200,12 @@ public class UserAuthPublicKey extends AbstractUserAuth implements SignatureFact
             throw new SignatureException("Key verification failed");
         }
 
+        if (previouslyAuthenticatedKeys == null) {
+            previouslyAuthenticatedKeys = new ArrayList<>();
+            session.setAttribute(AUTHENTICATED_KEYS, previouslyAuthenticatedKeys);
+        }
+        previouslyAuthenticatedKeys.add(presentedKey);
+
         if (debugEnabled) {
             log.debug("doAuth({}@{}) key type={}, fingerprint={} - verified",
                     username, session, alg, KeyUtils.getFingerPrint(key));
@@ -196,6 +214,13 @@ public class UserAuthPublicKey extends AbstractUserAuth implements SignatureFact
         return Boolean.TRUE;
     }
 
+    protected boolean alreadyAuthenticated(PublicKey key, List<PublicKey> previouslyAuthenticatedKeys) {
+        if (GenericUtils.isEmpty(previouslyAuthenticatedKeys)) {
+            return false;
+        }
+        return previouslyAuthenticatedKeys.stream().anyMatch(k -> KeyUtils.compareKeys(key, k));
+    }
+
     protected void verifyCertificateSignature(ServerSession session, OpenSshCertificate cert) throws Exception {
         PublicKey signatureKey = cert.getCaPubKey();
         String keyAlg = KeyUtils.getKeyType(signatureKey);
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/auth/CertificateReuseMultiAuthTest.java b/sshd-core/src/test/java/org/apache/sshd/server/auth/CertificateReuseMultiAuthTest.java
new file mode 100644
index 000000000..19eba24be
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/server/auth/CertificateReuseMultiAuthTest.java
@@ -0,0 +1,112 @@
+/*
+ * 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.server.auth;
+
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.security.PublicKey;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.sshd.certificate.OpenSshCertificateBuilder;
+import org.apache.sshd.client.SshClient;
+import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.common.SshException;
+import org.apache.sshd.common.auth.UserAuthMethodFactory;
+import org.apache.sshd.common.config.keys.AuthorizedKeyEntry;
+import org.apache.sshd.common.config.keys.KeyUtils;
+import org.apache.sshd.common.config.keys.OpenSshCertificate;
+import org.apache.sshd.common.config.keys.PublicKeyEntry;
+import org.apache.sshd.common.config.keys.PublicKeyEntryResolver;
+import org.apache.sshd.core.CoreModuleProperties;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.server.auth.pubkey.AuthorizedKeyEntriesPublickeyAuthenticator;
+import org.apache.sshd.util.test.BaseTestSupport;
+import org.apache.sshd.util.test.CoreTestSupportUtils;
+import org.junit.jupiter.api.Test;
+
+class CertificateReuseMultiAuthTest extends BaseTestSupport {
+
+    @Test
+    void twoCertificatesForOnePrivateKeyMustNotSatisfyTwoPublicKeySteps() throws Exception {
+        KeyPairGenerator generator = KeyPairGenerator.getInstance(KeyUtils.RSA_ALGORITHM);
+        generator.initialize(2048);
+        KeyPair ca = generator.generateKeyPair();
+        KeyPair user = generator.generateKeyPair();
+        KeyPair independentUser = generator.generateKeyPair();
+        String username = "single-key-user";
+        long expiry = System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1);
+
+        OpenSshCertificate cert1 = OpenSshCertificateBuilder.userCertificate()
+                .serial(1L).publicKey(user.getPublic()).id("first")
+                .validBefore(expiry).principals(Collections.singletonList(username))
+                .sign(ca, "rsa-sha2-256");
+        OpenSshCertificate cert2 = OpenSshCertificateBuilder.userCertificate()
+                .serial(2L).publicKey(user.getPublic()).id("second")
+                .validBefore(expiry).principals(Collections.singletonList(username))
+                .sign(ca, "rsa-sha2-256");
+        OpenSshCertificate independentCert = OpenSshCertificateBuilder.userCertificate()
+                .serial(3L).publicKey(independentUser.getPublic()).id("independent")
+                .validBefore(expiry).principals(Collections.singletonList(username))
+                .sign(ca, "rsa-sha2-256");
+        assertFalse(KeyUtils.compareKeys((PublicKey) cert1, (PublicKey) cert2));
+        assertTrue(KeyUtils.compareKeys(cert1.getCertPubKey(), cert2.getCertPubKey()));
+
+        SshServer sshd = CoreTestSupportUtils.setupTestServer(CertificateReuseMultiAuthTest.class);
+        SshClient client = CoreTestSupportUtils.setupTestClient(CertificateReuseMultiAuthTest.class);
+        try {
+            CoreTestSupportUtils.setupFullSignaturesSupport(sshd);
+            CoreTestSupportUtils.setupFullSignaturesSupport(client);
+            AuthorizedKeyEntry caEntry = AuthorizedKeyEntry.parseAuthorizedKeyEntry(
+                    "cert-authority " + PublicKeyEntry.toString(ca.getPublic()));
+            sshd.setPublickeyAuthenticator(new AuthorizedKeyEntriesPublickeyAuthenticator(
+                    "test-ca", null, Collections.singletonList(caEntry), PublicKeyEntryResolver.FAILING));
+            CoreModuleProperties.AUTH_METHODS.set(sshd, "publickey,publickey");
+            sshd.start();
+            client.setUserAuthFactoriesNames(UserAuthMethodFactory.PUBLIC_KEY);
+            client.start();
+
+            try (ClientSession session = createClientSession(username, client, sshd.getPort())) {
+                session.setKeyIdentityProvider(context -> Collections.singletonList(
+                        new KeyPair(cert1, user.getPrivate())));
+                assertThrows(SshException.class, () -> session.auth().verify(AUTH_TIMEOUT),
+                        "one certificate alone should not meet a two-key policy");
+                assertFalse(session.isAuthenticated());
+            }
+            try (ClientSession session = createClientSession(username, client, sshd.getPort())) {
+                session.setKeyIdentityProvider(context -> Arrays.asList(
+                        new KeyPair(cert1, user.getPrivate()),
+                        new KeyPair(independentCert, independentUser.getPrivate())));
+                session.auth().verify(AUTH_TIMEOUT);
+                assertTrue(session.isAuthenticated(), "two independent private keys should authenticate");
+            }
+            try (ClientSession session = createClientSession(username, client, sshd.getPort())) {
+                session.setKeyIdentityProvider(context -> Arrays.asList(
+                        new KeyPair(cert1, user.getPrivate()),
+                        new KeyPair(cert2, user.getPrivate())));
+                assertThrows(SshException.class, () -> session.auth().verify(AUTH_TIMEOUT),
+                        "two certificates for the same private key must not count as two keys");
+            }
+        } finally {
+            client.stop();
+            sshd.stop(true);
+        }
+    }
+}
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/auth/PublicKeyMultiAuthTest.java b/sshd-core/src/test/java/org/apache/sshd/server/auth/PublicKeyMultiAuthTest.java
new file mode 100644
index 000000000..cb672257f
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/server/auth/PublicKeyMultiAuthTest.java
@@ -0,0 +1,124 @@
+/*
+ * 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.server.auth;
+
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.sshd.client.SshClient;
+import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.common.SshException;
+import org.apache.sshd.common.auth.UserAuthMethodFactory;
+import org.apache.sshd.common.config.keys.AuthorizedKeyEntry;
+import org.apache.sshd.common.config.keys.KeyUtils;
+import org.apache.sshd.common.config.keys.PublicKeyEntry;
+import org.apache.sshd.common.config.keys.PublicKeyEntryResolver;
+import org.apache.sshd.core.CoreModuleProperties;
+import org.apache.sshd.server.SshServer;
+import org.apache.sshd.server.auth.hostbased.RejectAllHostBasedAuthenticator;
+import org.apache.sshd.server.auth.pubkey.AuthorizedKeyEntriesPublickeyAuthenticator;
+import org.apache.sshd.util.test.BaseTestSupport;
+import org.apache.sshd.util.test.CoreTestSupportUtils;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+class PublicKeyMultiAuthTest extends BaseTestSupport {
+
+    private static final String USER_NAME = "single-key-user";
+
+    private SshServer sshd;
+    private SshClient client;
+    private KeyPair firstAuthorizedKey;
+    private KeyPair secondAuthorizedKey;
+    private int port;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        KeyPairGenerator generator = KeyPairGenerator.getInstance(KeyUtils.RSA_ALGORITHM);
+        generator.initialize(2048);
+        firstAuthorizedKey = generator.generateKeyPair();
+        secondAuthorizedKey = generator.generateKeyPair();
+
+        sshd = CoreTestSupportUtils.setupTestServer(PublicKeyMultiAuthTest.class);
+        sshd.setHostBasedAuthenticator(RejectAllHostBasedAuthenticator.INSTANCE);
+        AuthorizedKeyEntry firstEntry = AuthorizedKeyEntry.parseAuthorizedKeyEntry(
+                PublicKeyEntry.toString(firstAuthorizedKey.getPublic()));
+        AuthorizedKeyEntry secondEntry = AuthorizedKeyEntry.parseAuthorizedKeyEntry(
+                PublicKeyEntry.toString(secondAuthorizedKey.getPublic()));
+        sshd.setPublickeyAuthenticator(new AuthorizedKeyEntriesPublickeyAuthenticator(
+                "two-authorized-keys", null, Arrays.asList(firstEntry, secondEntry), PublicKeyEntryResolver.FAILING));
+        CoreModuleProperties.AUTH_METHODS.set(sshd, "publickey,publickey");
+        sshd.start();
+        port = sshd.getPort();
+
+        client = CoreTestSupportUtils.setupTestClient(PublicKeyMultiAuthTest.class);
+        client.setUserAuthFactoriesNames(UserAuthMethodFactory.PUBLIC_KEY);
+        client.start();
+    }
+
+    @AfterEach
+    void tearDown() throws Exception {
+        if (client != null) {
+            client.stop();
+        }
+        if (sshd != null) {
+            sshd.stop(true);
+        }
+    }
+
+    @Test
+    void singleOfferedIdentityDoesNotSatisfyTwoPublicKeySteps() throws Exception {
+        try (ClientSession session = createClientSession(USER_NAME, client, port)) {
+            session.setKeyIdentityProvider(context -> Collections.singletonList(firstAuthorizedKey));
+            assertThrows(SshException.class, () -> session.auth().verify(AUTH_TIMEOUT));
+            assertFalse(session.isAuthenticated());
+        }
+    }
+
+    @Test
+    void repeatedSameKeyDoesNotSatisfyTwoPublicKeySteps() throws Exception {
+        try (ClientSession session = createClientSession(USER_NAME, client, port)) {
+            session.setKeyIdentityProvider(context -> {
+                List<KeyPair> maliciousIdentities = new ArrayList<>();
+                maliciousIdentities.add(firstAuthorizedKey);
+                maliciousIdentities.add(firstAuthorizedKey);
+                return maliciousIdentities;
+            });
+
+            SshException e = assertThrows(SshException.class, () -> session.auth().verify(AUTH_TIMEOUT),
+                    "one key must not satisfy two-key authentication policy");
+            assertEquals(e.getMessage(), "No more authentication methods available");
+        }
+    }
+
+    @Test
+    void twoDistinctAuthorizedKeysSatisfyTwoPublicKeySteps() throws Exception {
+        try (ClientSession session = createClientSession(USER_NAME, client, port)) {
+            session.setKeyIdentityProvider(context -> Arrays.asList(firstAuthorizedKey, secondAuthorizedKey));
+
+            session.auth().verify(AUTH_TIMEOUT);
+            assertTrue(session.isAuthenticated());
+        }
+    }
+}


(mina-sshd) 07/18: sshd-git: also strip --output= and -o= arguments from archive

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit b89e9627063decec9fd2b8c80c1950402e64af3a
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Fri Sep 18 19:56:21 2026 +0200

    sshd-git: also strip --output= and -o= arguments from archive
    
    Handle not only "--output file" but also "--output=file", and likewise
    for "-o".
    
    Unfortunately there is no reasonable way to hook into the JGit code to
    simply force use of stdout after the command arguments have been parsed,
    so we must remove the offending options beforehand.
---
 .../apache/sshd/git/pgm/EmbeddedCommandRunner.java |  3 +-
 .../org/apache/sshd/git/pgm/GitPgmCommandTest.java | 87 ++++++++++++++++++----
 2 files changed, 75 insertions(+), 15 deletions(-)

diff --git a/sshd-git/src/main/java/org/apache/sshd/git/pgm/EmbeddedCommandRunner.java b/sshd-git/src/main/java/org/apache/sshd/git/pgm/EmbeddedCommandRunner.java
index 0338a341e..5c72b20f5 100644
--- a/sshd-git/src/main/java/org/apache/sshd/git/pgm/EmbeddedCommandRunner.java
+++ b/sshd-git/src/main/java/org/apache/sshd/git/pgm/EmbeddedCommandRunner.java
@@ -202,7 +202,8 @@ public class EmbeddedCommandRunner {
                 if (a.hasNext()) {
                     a.next();
                 }
-            } else {
+            } else if (!opt.startsWith("--output=") && !opt.startsWith("-o=") //
+                    && !opt.startsWith("--output ") && !opt.startsWith("-o ")) {
                 result.add(opt);
             }
         }
diff --git a/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java b/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java
index 1a5fec73b..cff1129d2 100644
--- a/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java
+++ b/sshd-git/src/test/java/org/apache/sshd/git/pgm/GitPgmCommandTest.java
@@ -20,6 +20,7 @@ package org.apache.sshd.git.pgm;
 
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
+import java.io.File;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
@@ -72,6 +73,8 @@ class GitPgmCommandTest extends GitTestSupport {
     }
 
     private void runGitCommands(String testName, int port, Path serverDir) throws Exception {
+        Path repo = serverDir.resolve(testName);
+        Path cwd = new File(".").getCanonicalFile().toPath();
         try (SshClient client = setupTestClient()) {
             client.start();
             try (ClientSession session = client.connect(testName, SshdSocketAddress.LOCALHOST_IPV4, port)
@@ -79,7 +82,6 @@ class GitPgmCommandTest extends GitTestSupport {
                 session.addPasswordIdentity(testName);
                 session.auth().verify(AUTH_TIMEOUT);
 
-                Path repo = serverDir.resolve(testName);
                 Path readmeFile;
                 try (Git git = Git.init().setDirectory(repo.toFile()).call()) {
                     readmeFile = Files.write(repo.resolve("readme.txt"), Collections.singletonList("README"));
@@ -111,22 +113,79 @@ class GitPgmCommandTest extends GitTestSupport {
                         StandardCharsets.UTF_8, AUTH_TIMEOUT);
                 assertFalse(Files.exists(repo.resolve("archive.zip")));
                 assertFalse(Files.exists(serverDir.resolve("archive.zip")));
-                ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
-                try (ZipInputStream zIn = new ZipInputStream(in)) {
-                    ZipEntry entry = zIn.getNextEntry();
-                    assertEquals(readmeFile.getFileName().toString(), entry.getName());
-                    ByteArrayOutputStream content = new ByteArrayOutputStream();
-                    byte[] chunk = new byte[1024];
-                    int n = 0;
-                    while ((n = zIn.read(chunk)) >= 0) {
-                        content.write(chunk, 0, n);
-                    }
-                    zIn.closeEntry();
-                    assertEquals(Files.size(readmeFile), content.size());
-                }
+                assertFalse(Files.exists(cwd.resolve("archive.zip")));
+                checkStream(out.toByteArray(), readmeFile);
+                out.reset();
+                err.reset();
+                session.executeRemoteCommand(commandPrefix + " archive --output archive.zip --format zip HEAD", out, err,
+                        StandardCharsets.UTF_8, AUTH_TIMEOUT);
+                assertFalse(Files.exists(repo.resolve("archive.zip")));
+                assertFalse(Files.exists(serverDir.resolve("archive.zip")));
+                assertFalse(Files.exists(cwd.resolve("archive.zip")));
+                checkStream(out.toByteArray(), readmeFile);
+                out.reset();
+                err.reset();
+                session.executeRemoteCommand(commandPrefix + " archive -o=archive.zip --format zip HEAD", out, err,
+                        StandardCharsets.UTF_8, AUTH_TIMEOUT);
+                assertFalse(Files.exists(repo.resolve("archive.zip")));
+                assertFalse(Files.exists(serverDir.resolve("archive.zip")));
+                assertFalse(Files.exists(cwd.resolve("archive.zip")));
+                checkStream(out.toByteArray(), readmeFile);
+                out.reset();
+                err.reset();
+                session.executeRemoteCommand(commandPrefix + " archive --output=archive.zip --format zip HEAD", out, err,
+                        StandardCharsets.UTF_8, AUTH_TIMEOUT);
+                assertFalse(Files.exists(repo.resolve("archive.zip")));
+                assertFalse(Files.exists(serverDir.resolve("archive.zip")));
+                assertFalse(Files.exists(cwd.resolve("archive.zip")));
+                checkStream(out.toByteArray(), readmeFile);
+                out.reset();
+                err.reset();
+                // JGit's Archive command uses Kohsuke's args4j, which has a bug: it also attempts to handle single
+                // command line arguments using a blank as delimiter between key and value, but then takes the whole
+                // argument as value. If the single "--output archive.zip" argument is not removed from the following
+                // command, Archive will actually write a file at cwd named "--output archive.zip".
+                session.executeRemoteCommand(commandPrefix + " archive \"--output archive.zip\" --format zip HEAD", out, err,
+                        StandardCharsets.UTF_8, AUTH_TIMEOUT);
+                assertFalse(Files.exists(repo.resolve("archive.zip")));
+                assertFalse(Files.exists(serverDir.resolve("archive.zip")));
+                assertFalse(Files.exists(cwd.resolve("archive.zip")));
+                assertFalse(Files.exists(cwd.resolve("--output archive.zip")));
+                checkStream(out.toByteArray(), readmeFile);
+                out.reset();
+                err.reset();
+                session.executeRemoteCommand(commandPrefix + " archive \"-o archive.zip\" --format zip HEAD", out, err,
+                        StandardCharsets.UTF_8, AUTH_TIMEOUT);
+                assertFalse(Files.exists(repo.resolve("archive.zip")));
+                assertFalse(Files.exists(serverDir.resolve("archive.zip")));
+                assertFalse(Files.exists(cwd.resolve("archive.zip")));
+                assertFalse(Files.exists(cwd.resolve("-o archive.zip")));
+                checkStream(out.toByteArray(), readmeFile);
             } finally {
                 client.stop();
+                Files.deleteIfExists(repo.resolve("archive.zip"));
+                Files.deleteIfExists(serverDir.resolve("archive.zip"));
+                Files.deleteIfExists(cwd.resolve("archive.zip"));
+                Files.deleteIfExists(cwd.resolve("--output archive.zip"));
+                Files.deleteIfExists(cwd.resolve("-o archive.zip"));
+            }
+        }
+    }
+
+    private void checkStream(byte[] stdout, Path readmeFile) throws Exception {
+        ByteArrayInputStream in = new ByteArrayInputStream(stdout);
+        try (ZipInputStream zIn = new ZipInputStream(in)) {
+            ZipEntry entry = zIn.getNextEntry();
+            assertNotNull(entry);
+            assertEquals(readmeFile.getFileName().toString(), entry.getName());
+            ByteArrayOutputStream content = new ByteArrayOutputStream();
+            byte[] chunk = new byte[1024];
+            int n = 0;
+            while ((n = zIn.read(chunk)) >= 0) {
+                content.write(chunk, 0, n);
             }
+            zIn.closeEntry();
+            assertEquals(Files.size(readmeFile), content.size());
         }
     }
 }


(mina-sshd) 13/18: PublicKeyAuthenticator.authenticate(): remove AsyncAuthException

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 602896f3e418ed1ec025feabadb1eecb2cb5f397
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Thu Sep 24 23:11:41 2026 +0200

    PublicKeyAuthenticator.authenticate(): remove AsyncAuthException
    
    Removing an unchecked exception from the interface is source and binary
    compatible. Asynchronous authentication is not supported for public key
    authentication.
---
 .../org/apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java    | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java b/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java
index 703c5887d..2ef3dfc37 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/auth/pubkey/PublickeyAuthenticator.java
@@ -26,7 +26,6 @@ import java.util.Collection;
 import org.apache.sshd.common.config.keys.AuthorizedKeyEntry;
 import org.apache.sshd.common.config.keys.PublicKeyEntryResolver;
 import org.apache.sshd.common.util.GenericUtils;
-import org.apache.sshd.server.auth.AsyncAuthException;
 import org.apache.sshd.server.session.ServerSession;
 
 /**
@@ -49,9 +48,8 @@ public interface PublickeyAuthenticator {
      * @param  key                the key
      * @param  session            the server session
      * @return                    {@code true} if the key may be used; {@code false} otherwise
-     * @throws AsyncAuthException If the authentication is performed asynchronously
      */
-    boolean authenticate(String username, PublicKey key, ServerSession session) throws AsyncAuthException;
+    boolean authenticate(String username, PublicKey key, ServerSession session);
 
     /**
      * @param  id                       Some kind of mnemonic identifier for the authenticator - used also in


(mina-sshd) 14/18: Update CHANGES.md

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 1c97396ff1d52e39b044e4fdbcb040898d15cae6
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Tue Sep 22 21:12:47 2026 +0200

    Update CHANGES.md
---
 CHANGES.md | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/CHANGES.md b/CHANGES.md
index 4977c9048..a96974787 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -36,6 +36,14 @@
 * [GH-656](https://github.com/apache/mina-sshd/issues/656) `ChannelPipedInputStream`: shrink buffer when emptied
 * [GH-906](https://github.com/apache/mina-sshd/issues/906) Fix finding a signature factory for BC ed25519 keys
 * [GH-911](https://github.com/apache/mina-sshd/issues/911) Fix server-side SOCKS5 proxy for fragmented and pipelined CONNECT requests
+* Allow asynchronous authentication only for password and keyboard-interactive authentication schemes
+* Fix authentication requiring multiple public keys (server-side)
+* Better argument handling in sshd-git
+* More checks in authentication (server-side)
+* Better SCP command handling
+* Simplify SFTP response message handling
+* Fix check-file-name/check-file-handle SFTP v6 extension
+* Improve LDAP authentication (sshd-ldap)
 
 ## New Features
 


(mina-sshd) 10/18: Fix check-file-name/check-file-handle SFTP v6 extension

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit f4f562c29e22ed98479405e8bec58611f2faceba
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Sat Sep 19 22:50:06 2026 +0200

    Fix check-file-name/check-file-handle SFTP v6 extension
    
    Using a small blockSize on a huge file may generate too many hashes.
    Accumulating them all in a buffer may exhaust the memory.  Since most
    SFTP implementations have a limit on the length of SFTP messages,
    abort if the buffer gets longer than 256kB.
    
    Additionally change the block logic. For a large block size, the
    previous implementation would allocate a large buffer. Try this with
    a 1TB file and a 4GB block size... Change this to keep the block size a
    logical size, and use a fixed-size small buffer to accumulate the digest
    over large blocks.
---
 .../sshd/sftp/client/impl/DefaultSftpClient.java   |   2 +-
 .../org/apache/sshd/sftp/common/SftpConstants.java |   3 +
 .../sftp/server/AbstractSftpSubsystemHelper.java   | 113 ++++++++++-----------
 3 files changed, 60 insertions(+), 58 deletions(-)

diff --git a/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/DefaultSftpClient.java b/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/DefaultSftpClient.java
index 422dc5b81..5bc41b284 100644
--- a/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/DefaultSftpClient.java
+++ b/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/DefaultSftpClient.java
@@ -230,7 +230,7 @@ public class DefaultSftpClient extends AbstractSftpClient {
             if (length < 5) {
                 throw new IOException("Illegal sftp packet length: " + length);
             }
-            if (length > (8 * SshConstants.SSH_REQUIRED_PAYLOAD_PACKET_LENGTH_SUPPORT)) {
+            if (length > SftpConstants.MAX_SFTP_MESSAGE_LENGTH) {
                 throw new StreamCorruptedException("Illogical sftp packet length: " + length);
             }
             if ((wpos - rpos) >= (length + 4)) {
diff --git a/sshd-sftp/src/main/java/org/apache/sshd/sftp/common/SftpConstants.java b/sshd-sftp/src/main/java/org/apache/sshd/sftp/common/SftpConstants.java
index b95a87736..cc0e5e079 100644
--- a/sshd-sftp/src/main/java/org/apache/sshd/sftp/common/SftpConstants.java
+++ b/sshd-sftp/src/main/java/org/apache/sshd/sftp/common/SftpConstants.java
@@ -21,6 +21,7 @@ package org.apache.sshd.sftp.common;
 import java.util.Collections;
 import java.util.Map;
 
+import org.apache.sshd.common.SshConstants;
 import org.apache.sshd.common.util.GenericUtils;
 import org.apache.sshd.common.util.logging.LoggingUtils;
 
@@ -274,6 +275,8 @@ public final class SftpConstants {
     public static final int SSH_ACL_CAP_INHERIT_ACCESS = 0x00000010;
     public static final int SSH_ACL_CAP_INHERIT_AUDIT_ALARM = 0x00000020;
 
+    public static final int MAX_SFTP_MESSAGE_LENGTH = 8 * SshConstants.SSH_REQUIRED_PAYLOAD_PACKET_LENGTH_SUPPORT; // 256kB
+
     private SftpConstants() {
         throw new UnsupportedOperationException("No instance");
     }
diff --git a/sshd-sftp/src/main/java/org/apache/sshd/sftp/server/AbstractSftpSubsystemHelper.java b/sshd-sftp/src/main/java/org/apache/sshd/sftp/server/AbstractSftpSubsystemHelper.java
index a2e66fcf3..347fe8021 100755
--- a/sshd-sftp/src/main/java/org/apache/sshd/sftp/server/AbstractSftpSubsystemHelper.java
+++ b/sshd-sftp/src/main/java/org/apache/sshd/sftp/server/AbstractSftpSubsystemHelper.java
@@ -911,14 +911,14 @@ public abstract class AbstractSftpSubsystemHelper
         String[] algos = GenericUtils.split(algList, ',');
         long startOffset = buffer.getLong();
         long length = buffer.getLong();
-        int blockSize = buffer.getInt();
+        long blockSize = buffer.getUInt();
         try {
             buffer = prepareReply(buffer);
             buffer.putByte((byte) SftpConstants.SSH_FXP_EXTENDED_REPLY);
             buffer.putInt(id);
             buffer.putString(SftpConstants.EXT_CHECK_FILE);
             doCheckFileHash(id, targetType, target,
-                    Arrays.asList(algos), startOffset, length, blockSize, buffer);
+                    Arrays.asList(algos), startOffset, length, (int) blockSize, buffer);
         } catch (Exception e) {
             sendStatus(prepareReply(buffer), id, e,
                     SftpConstants.SSH_FXP_EXTENDED, targetType, target,
@@ -929,14 +929,18 @@ public abstract class AbstractSftpSubsystemHelper
         send(buffer);
     }
 
+    protected abstract void doCheckFileHash(
+            int id, String targetType, String target, Collection<String> algos,
+            long startOffset, long length, int blockSize, Buffer buffer) throws Exception;
+
     protected void doCheckFileHash(
             int id, Path file, NamedFactory<? extends Digest> factory,
-            long startOffset, long length, int blockSize, Buffer buffer)
+            long startOffset, long length, int unsignedBlockSize, Buffer buffer)
             throws Exception {
         ValidateUtils.checkTrue(startOffset >= 0L, "Invalid start offset: %d", startOffset);
         ValidateUtils.checkTrue(length >= 0L, "Invalid length: %d", length);
-        ValidateUtils.checkTrue(
-                (blockSize == 0) || (blockSize >= SftpConstants.MIN_CHKFILE_BLOCKSIZE),
+        long blockSize = unsignedBlockSize & 0xFFFF_FFFFL;
+        ValidateUtils.checkTrue(blockSize == 0 || blockSize >= SftpConstants.MIN_CHKFILE_BLOCKSIZE,
                 "Invalid block size: %d", blockSize);
         Objects.requireNonNull(factory, "No digest factory provided");
         buffer.putString(factory.getName());
@@ -954,14 +958,11 @@ public abstract class AbstractSftpSubsystemHelper
         ValidateUtils.checkTrue(effectiveLength > 0L,
                 "Non-positive effective hash data length: %d", effectiveLength);
 
-        byte[] digestBuf = (blockSize == 0)
-                ? new byte[Math.min((int) effectiveLength, IoUtils.DEFAULT_COPY_SIZE)]
-                : new byte[Math.min((int) effectiveLength, blockSize)];
+        byte[] digestBuf = new byte[IoUtils.DEFAULT_COPY_SIZE];
         ByteBuffer wb = ByteBuffer.wrap(digestBuf);
         SftpFileSystemAccessor accessor = getFileSystemAccessor();
         ServerSession session = getServerSession();
-        try (SeekableByteChannel channel = accessor.openFile(
-                this, null, file, null, Collections.emptySet())) {
+        try (SeekableByteChannel channel = accessor.openFile(this, null, file, null, Collections.emptySet())) {
             channel.position(startOffset);
 
             Digest digest = factory.create();
@@ -969,59 +970,62 @@ public abstract class AbstractSftpSubsystemHelper
 
             boolean traceEnabled = log.isTraceEnabled();
             if (blockSize == 0) {
-                while (effectiveLength > 0L) {
-                    int remainLen = Math.min(digestBuf.length, (int) effectiveLength);
-                    ByteBuffer bb = wb;
-                    if (remainLen < digestBuf.length) {
-                        bb = ByteBuffer.wrap(digestBuf, 0, remainLen);
-                    }
-                    bb.clear(); // prepare for next read
-
-                    int readLen = channel.read(bb);
-                    if (readLen < 0) {
-                        break;
-                    }
+                blockSize = effectiveLength;
+            }
 
-                    effectiveLength -= readLen;
-                    digest.update(digestBuf, 0, readLen);
+            long originalLength = effectiveLength;
+            for (int count = 0; effectiveLength > 0L; count++) {
+                if (buffer.available() > SftpConstants.MAX_SFTP_MESSAGE_LENGTH) {
+                    throw new IllegalArgumentException(
+                            "Too many file hashes. Use a larger block size or a smaller file chunk. (Block size = "
+                                                       + blockSize + ", chunk size = " + originalLength + ')');
                 }
-
-                byte[] hashValue = digest.digest();
+                long toHash = Math.min(blockSize, effectiveLength);
+                long hashed = hashOneBlock(digest, channel, digestBuf, wb, toHash);
+                if (hashed == 0 && channel.position() >= startOffset) {
+                    // Last block had exhausted the file; no need to write a digest for a zero-length input.
+                    break;
+                } else if (hashed < toHash) {
+                    // Hashed the last bit, then hit (early) EOF: we're done once we've written the last digest
+                    effectiveLength = 0;
+                } else {
+                    effectiveLength -= toHash;
+                }
+                byte[] hashValue = digest.digest(); // NOTE: this also resets the hash for the next read
                 if (traceEnabled) {
-                    log.trace("doCheckFileHash({})[{}] offset={}, length={} - algo={}, hash={}",
-                            session, file, startOffset, length,
-                            digest.getAlgorithm(), BufferUtils.toHex(':', hashValue));
+                    log.trace("doCheckFileHash({})({})[{}] offset={}, length={} - algo={}, hash={}", session, count, file,
+                            startOffset, length, digest.getAlgorithm(), BufferUtils.toHex(':', hashValue));
                 }
                 buffer.putBytes(hashValue);
-            } else {
-                for (int count = 0; effectiveLength > 0L; count++) {
-                    int remainLen = Math.min(digestBuf.length, (int) effectiveLength);
-                    ByteBuffer bb = wb;
-                    if (remainLen < digestBuf.length) {
-                        bb = ByteBuffer.wrap(digestBuf, 0, remainLen);
-                    }
-                    bb.clear(); // prepare for next read
+            }
 
-                    int readLen = channel.read(bb);
-                    if (readLen < 0) {
-                        break;
-                    }
+            accessor.closeFile(this, null, file, null, channel, Collections.emptySet());
+        }
+    }
 
-                    effectiveLength -= readLen;
-                    digest.update(digestBuf, 0, readLen);
+    private long hashOneBlock(
+            Digest digest, SeekableByteChannel channel, byte[] digestBuf, ByteBuffer fullBuffer,
+            long blockSize) throws Exception {
+        long effectiveLength = blockSize;
+        long hashed = 0;
+        while (effectiveLength > 0L) {
+            int remainLen = (int) Math.min(digestBuf.length, effectiveLength);
+            ByteBuffer bb = fullBuffer;
+            if (remainLen < digestBuf.length) {
+                bb = ByteBuffer.wrap(digestBuf, 0, remainLen);
+            }
+            bb.clear(); // prepare for next read
 
-                    byte[] hashValue = digest.digest(); // NOTE: this also resets the hash for the next read
-                    if (traceEnabled) {
-                        log.trace("doCheckFileHash({})({})[{}] offset={}, length={} - algo={}, hash={}",
-                                session, file, count, startOffset, length,
-                                digest.getAlgorithm(), BufferUtils.toHex(':', hashValue));
-                    }
-                    buffer.putBytes(hashValue);
-                }
+            int readLen = channel.read(bb);
+            if (readLen < 0) {
+                break;
             }
 
-            accessor.closeFile(this, null, file, null, channel, Collections.emptySet());
+            effectiveLength -= readLen;
+            digest.update(digestBuf, 0, readLen);
+            hashed += readLen;
         }
+        return hashed;
     }
 
     protected void doMD5Hash(Buffer buffer, int id, String targetType) throws IOException {
@@ -1164,11 +1168,6 @@ public abstract class AbstractSftpSubsystemHelper
         return hashValue;
     }
 
-    protected abstract void doCheckFileHash(
-            int id, String targetType, String target, Collection<String> algos,
-            long startOffset, long length, int blockSize, Buffer buffer)
-            throws Exception;
-
     protected void doReadLink(Buffer buffer, int id) throws IOException {
         String path = buffer.getString();
         Map.Entry<Path, String> link;


(mina-sshd) 11/18: Fix LDAP authentication

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit acc0f1ed436529c24f6677da83e7ec4e3537c4c9
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Sat Sep 19 23:09:00 2026 +0200

    Fix LDAP authentication
    
    Properly encode filter parameters following RFC 4515, and encode
    parameters for the distinguished name following RFC 4514. Also harden
    the password authenticator by requiring a non-empty result from LDAP.
---
 .../org/apache/sshd/ldap/LdapNetworkConnector.java | 75 +++++++++++++++++++++-
 .../sshd/ldap/LdapPasswordAuthenticator.java       |  6 +-
 .../org/apache/sshd/ldap/LdapEncodingTest.java     | 47 ++++++++++++++
 .../sshd/ldap/LdapPasswordAuthenticatorTest.java   | 10 ++-
 .../sshd/ldap/LdapPublickeyAuthenticatorTest.java  | 14 ++--
 5 files changed, 137 insertions(+), 15 deletions(-)

diff --git a/sshd-ldap/src/main/java/org/apache/sshd/ldap/LdapNetworkConnector.java b/sshd-ldap/src/main/java/org/apache/sshd/ldap/LdapNetworkConnector.java
index 5be56e073..d6ce5c522 100644
--- a/sshd-ldap/src/main/java/org/apache/sshd/ldap/LdapNetworkConnector.java
+++ b/sshd-ldap/src/main/java/org/apache/sshd/ldap/LdapNetworkConnector.java
@@ -19,6 +19,7 @@
 
 package org.apache.sshd.ldap;
 
+import java.nio.charset.StandardCharsets;
 import java.text.MessageFormat;
 import java.util.ArrayList;
 import java.util.Arrays;
@@ -88,6 +89,9 @@ public class LdapNetworkConnector<C> extends NetworkConnector {
               + ",userPassword,userCertificate,cACertificate,authorityRevocationList,certificateRevocationList"
               + ",crossCertificatePair,x500UniqueIdentifier";
 
+    private static final char[] HEX = new char[] {
+            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
+
     protected final SearchControls searchControls = new SearchControls();
     protected final Map<String, Object> ldapEnv = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
     protected MessageFormat bindDNPattern = new MessageFormat(DEFAULT_LDAP_BIND_DN_PATTERN);
@@ -435,13 +439,14 @@ public class LdapNetworkConnector<C> extends NetworkConnector {
         String mode = Objects.toString(env.get(Context.SECURITY_AUTHENTICATION), null);
         boolean anonymous = GenericUtils.isEmpty(mode) || PropertyResolverUtils.isNoneValue(mode);
         if (!anonymous) {
-            Object[] bindParams = { username, password };
             if (!env.containsKey(Context.SECURITY_PRINCIPAL)) {
+                Object[] bindParams = { encodeDistinguishedName(username), encodeDistinguishedName(password) };
                 String bindDN = Objects.requireNonNull(bindDNPattern, "No bind DN pattern").format(bindParams);
                 env.put(Context.SECURITY_PRINCIPAL, ValidateUtils.checkNotNullAndNotEmpty(bindDN, "No bind DN"));
             }
 
             if (!env.containsKey(Context.SECURITY_CREDENTIALS)) {
+                Object[] bindParams = { username, password };
                 String bindPassword
                         = Objects.requireNonNull(bindPasswordPattern, "No bind password pattern").format(bindParams);
                 env.put(Context.SECURITY_CREDENTIALS, ValidateUtils.checkNotNullAndNotEmpty(bindPassword, "No bind password"));
@@ -453,13 +458,13 @@ public class LdapNetworkConnector<C> extends NetworkConnector {
 
     protected String resolveBaseDN(C queryContext, Map<?, ?> ldapConfig, String username, String password)
             throws NamingException {
-        Object[] bindParams = { username, password };
+        Object[] bindParams = { encodeDistinguishedName(username), encodeDistinguishedName(password) };
         return Objects.requireNonNull(baseDNPattern, "No base DN pattern").format(bindParams);
     }
 
     protected String resolveSearchFilter(C queryContext, Map<?, ?> ldapConfig, String username, String password)
             throws NamingException {
-        Object[] bindParams = { username, password };
+        Object[] bindParams = { encodeFilter(username), encodeFilter(password) };
         return Objects.requireNonNull(searchFilterPattern, "No search filter pattern").format(bindParams);
     }
 
@@ -552,4 +557,68 @@ public class LdapNetworkConnector<C> extends NetworkConnector {
 
         return attrVal.toString();
     }
+
+    /**
+     * Encodes a value following RFC 4515 for use in an LDAP filter template.
+     *
+     * @param  value to encode
+     * @return       the encoded value
+     * @see          <a href="https://www.rfc-editor.org/info/rfc4515/">RFC 4515</a>
+     */
+    public static String encodeFilter(String value) {
+        if (value == null) {
+            return "";
+        }
+        byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
+        StringBuilder sb = new StringBuilder(utf8.length);
+        for (byte b : utf8) {
+            int ch = b & 0xFF;
+            if (ch < ' ' || ch == '*' || ch == '(' || ch == ')' || ch == '\\' || ch >= 0x7F) {
+                sb.append('\\').append(HEX[ch >>> 4]).append(HEX[ch & 0x0F]);
+            } else {
+                sb.append((char) ch);
+            }
+        }
+        return sb.toString();
+    }
+
+    /**
+     * Encodes a value following RFC 4514 for use in an LDAP Distinguished Name.
+     *
+     * @param  value to encode
+     * @return       the encoded value
+     * @see          <a href="https://www.rfc-editor.org/info/rfc4514/">RFC 4514</a>
+     */
+    public static String encodeDistinguishedName(String value) {
+        if (value == null) {
+            return "";
+        }
+        // Note: javax.naming.ldap.Rdn.escapeValue() does not escape NUL nor other control characters. It escapes _all_
+        // leading and trailing spaces (and \r), and _all_ hashes. It implements RFC 2553, which didn't mention NUL and
+        // which was obsoleted by RFC 4514.
+        byte[] utf8 = value.getBytes(StandardCharsets.UTF_8);
+        StringBuilder sb = new StringBuilder(utf8.length);
+        for (int i = 0; i < utf8.length; i++) {
+            int ch = utf8[i] & 0xFF;
+            if (ch == ' ') {
+                if (i == 0 || i == utf8.length - 1) {
+                    sb.append('\\');
+                }
+                sb.append((char) ch);
+            } else if (ch == '#') {
+                if (i == 0) {
+                    sb.append('\\');
+                }
+                sb.append((char) ch);
+            } else if (ch == '"' || ch == '+' || ch == ',' || ch == ';' || ch == '<' || ch == '>' || ch == '\\') {
+                sb.append('\\').append((char) ch);
+            } else if (ch < ' ' || ch >= 0x7F) {
+                sb.append('\\').append(HEX[ch >>> 4]).append(HEX[ch & 0x0F]);
+            } else {
+                sb.append((char) ch);
+            }
+        }
+        return sb.toString();
+    }
+
 }
diff --git a/sshd-ldap/src/main/java/org/apache/sshd/ldap/LdapPasswordAuthenticator.java b/sshd-ldap/src/main/java/org/apache/sshd/ldap/LdapPasswordAuthenticator.java
index 3b3945ca2..bb7ba36bb 100644
--- a/sshd-ldap/src/main/java/org/apache/sshd/ldap/LdapPasswordAuthenticator.java
+++ b/sshd-ldap/src/main/java/org/apache/sshd/ldap/LdapPasswordAuthenticator.java
@@ -75,10 +75,6 @@ public class LdapPasswordAuthenticator extends LdapAuthenticator implements Pass
 
     protected boolean authenticate(
             String username, String password, ServerSession session, Map<String, ?> attrs) {
-        /*
-         * By default we assume that the user + password are the same for accessing the LDAP as the user's account, so
-         * the very LDAP query success is enough
-         */
-        return true;
+        return attrs != null && !attrs.isEmpty();
     }
 }
diff --git a/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapEncodingTest.java b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapEncodingTest.java
new file mode 100644
index 000000000..afff7e964
--- /dev/null
+++ b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapEncodingTest.java
@@ -0,0 +1,47 @@
+/*
+ * 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.ldap;
+
+import org.apache.sshd.util.test.JUnitTestSupport;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+
+@Tag("NoIoTestCase")
+public class LdapEncodingTest extends JUnitTestSupport {
+
+    @Test
+    void testEncodeFilter() {
+        assertEquals("\\00\\7F\\C3\\BF\\2A\\28\\29\\5Ca0B\\C3\\A4\\C3\\A9",
+                LdapNetworkConnector.encodeFilter("\000\177\377*()\\a0Bäé"));
+        assertEquals("Lu\\C4\\8Di\\C4\\87", LdapNetworkConnector.encodeFilter("Lučić")); // From RFC 4515
+    }
+
+    @Test
+    void testEncodeDN() {
+        assertEquals("J. Smith", LdapNetworkConnector.encodeDistinguishedName("J. Smith"));
+        assertEquals("James \\\"Jim\\\" Smith", LdapNetworkConnector.encodeDistinguishedName("James \"Jim\" Smith"));
+        assertEquals("Before\\0DAfter", LdapNetworkConnector.encodeDistinguishedName("Before\rAfter"));
+        assertEquals("Lu\\C4\\8Di\\C4\\87", LdapNetworkConnector.encodeDistinguishedName("Lučić"));
+        assertEquals("J\\C3\\B6rg M\\C3\\BCller", LdapNetworkConnector.encodeDistinguishedName("Jörg Müller"));
+        assertEquals("\\#foo", LdapNetworkConnector.encodeDistinguishedName("#foo"));
+        assertEquals("\\  foo \\ ", LdapNetworkConnector.encodeDistinguishedName("  foo  "));
+        assertEquals("\\  foo\\00\\+\\,\\;\\<\\>\\\\bar\\ ",
+                LdapNetworkConnector.encodeDistinguishedName("  foo\000+,;<>\\bar "));
+    }
+}
diff --git a/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPasswordAuthenticatorTest.java b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPasswordAuthenticatorTest.java
index 37ea3cbad..7414bc3a7 100644
--- a/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPasswordAuthenticatorTest.java
+++ b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPasswordAuthenticatorTest.java
@@ -35,9 +35,6 @@ import org.junit.jupiter.api.TestMethodOrder;
 import org.junit.jupiter.api.extension.ExtendWith;
 import org.mockito.Mockito;
 
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
 /**
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
@@ -73,6 +70,13 @@ public class LdapPasswordAuthenticatorTest extends BaseAuthenticatorTest {
         usersMap.forEach((username, password) -> {
             outputDebugMessage("Authenticate: user=%s, password=%s", username, password);
             assertTrue(auth.authenticate(username, password, session), "Failed to authenticate " + username);
+            String otherPassword = password + "bar";
+            outputDebugMessage("Authenticate: user=%s, password=%s", username, otherPassword);
+            assertFalse(auth.authenticate(username, otherPassword, session), "Should not have authenticated " + username);
         });
+        String otherUser = "other";
+        assertFalse(usersMap.containsKey(otherUser));
+        assertFalse(auth.authenticate(otherUser, otherUser, session), "Should not have authenticated other");
+        assertFalse(auth.authenticate("*", "*", session), "Should not have authenticated *");
     }
 }
diff --git a/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPublickeyAuthenticatorTest.java b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPublickeyAuthenticatorTest.java
index 827e2692f..07c788158 100644
--- a/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPublickeyAuthenticatorTest.java
+++ b/sshd-ldap/src/test/java/org/apache/sshd/ldap/LdapPublickeyAuthenticatorTest.java
@@ -19,6 +19,8 @@
 
 package org.apache.sshd.ldap;
 
+import java.security.KeyPair;
+import java.security.KeyPairGenerator;
 import java.security.PublicKey;
 import java.util.Collections;
 import java.util.Comparator;
@@ -43,9 +45,6 @@ import org.junit.jupiter.api.TestMethodOrder;
 import org.junit.jupiter.api.extension.ExtendWith;
 import org.mockito.Mockito;
 
-import static org.junit.jupiter.api.Assertions.assertFalse;
-import static org.junit.jupiter.api.Assertions.assertTrue;
-
 /**
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
@@ -88,12 +87,19 @@ public class LdapPublickeyAuthenticatorTest extends BaseAuthenticatorTest {
         auth.setKeyAttributeName(TEST_ATTR_NAME);
         auth.setRetrievedAttributes(TEST_ATTR_NAME);
 
+        KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA");
+        gen.initialize(1024);
+        KeyPair bogus = gen.generateKeyPair();
         ServerSession session = Mockito.mock(ServerSession.class);
         outputDebugMessage("%s: %s", getCurrentTestName(), auth);
         KEYS_MAP.forEach((username, key) -> {
             outputDebugMessage("Authenticate: user=%s, key-type=%s, fingerprint=%s",
                     username, KeyUtils.getKeyType(key), KeyUtils.getFingerPrint(key));
-            assertTrue(auth.authenticate(username, key, session), "Failed to authenticate user=" + username);
+            assertTrue(auth.authenticate(username, key, session), "Failed to authenticate user = " + username);
+            assertFalse(auth.authenticate(username, bogus.getPublic(), session),
+                    "Should not have authenticated user = " + username);
+            assertFalse(auth.authenticate("other", key, session), "Should not have authenticated user = other");
+            assertFalse(auth.authenticate("*", key, session), "Should not have authenticated user = *");
         });
     }
 }


(mina-sshd) 06/18: Improve sanity checks in UserAuthKeyboardInteractive

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 7704e7efbb80dce8036cb28f50907282248f63a7
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Tue Sep 22 19:01:39 2026 +0200

    Improve sanity checks in UserAuthKeyboardInteractive
    
    There already was a sanity check about the number of challenges on the
    client side -- but it allowed up to 32768 challenges. That's clearly
    nonsense. Limit this to the minimum of whatever may fit into the SSH
    packet and 100.
    
    On the server side, there was a similar sanity check for the number of
    challenge responses, equally nonsensical. But there, RFC 4256 even
    mandates that the number of responses must match the number of
    challenges sent exactly, so implement that.
---
 .../auth/keyboard/UserAuthKeyboardInteractive.java | 22 +++++++++++++++++++---
 .../auth/keyboard/UserAuthKeyboardInteractive.java | 11 +++++++----
 2 files changed, 26 insertions(+), 7 deletions(-)

diff --git a/sshd-core/src/main/java/org/apache/sshd/client/auth/keyboard/UserAuthKeyboardInteractive.java b/sshd-core/src/main/java/org/apache/sshd/client/auth/keyboard/UserAuthKeyboardInteractive.java
index c004e22d3..81361634b 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/auth/keyboard/UserAuthKeyboardInteractive.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/auth/keyboard/UserAuthKeyboardInteractive.java
@@ -39,6 +39,11 @@ import org.apache.sshd.core.CoreModuleProperties;
 public class UserAuthKeyboardInteractive extends AbstractUserAuth {
     public static final String NAME = UserAuthKeyboardInteractiveFactory.NAME;
 
+    // Still way too high to be practical (typical servers send maybe 1 to 3 challenges), but high enough to allow even
+    // really esoteric use cases while being low enough to be very comfortably able to allocate the arrays for the
+    // prompts and echo flags.
+    private static final int MAX_PROMPTS = 100;
+
     private final AtomicBoolean requestPending = new AtomicBoolean(false);
     private Iterator<String> passwords;
     private int maxAttempts;
@@ -120,11 +125,17 @@ public class UserAuthKeyboardInteractive extends AbstractUserAuth {
         String instruction = buffer.getString();
         String lang = buffer.getString();
         int num = buffer.getInt();
+        // Minimum length for one prompt is 6 bytes: 4 bytes string length of the prompt and at least one byte of data,
+        // plus one byte for the echo boolean.
+        int maxPrompts = buffer.available() / 6;
+        // Now maxPrompts can still be rather large (roughly 43690 -- we accept SSH packets up to 256kB). That many
+        // prompts make no sense.
+        maxPrompts = Math.min(maxPrompts, MAX_PROMPTS);
         // Protect against malicious or corrupted packets
-        if ((num < 0) || (num > SshConstants.SSH_REQUIRED_PAYLOAD_PACKET_LENGTH_SUPPORT)) {
-            log.error("processAuthDataRequest({})[{}] illogical challenges count ({}) for name={}, instruction={}",
+        if ((num < 0) || (num > maxPrompts)) {
+            log.warn("processAuthDataRequest({})[{}] illogical challenges count ({}) for name={}, instruction={}",
                     session, service, num, name, instruction);
-            throw new IndexOutOfBoundsException("Illogical challenges count: " + num);
+            return false;
         }
 
         boolean debugEnabled = log.isDebugEnabled();
@@ -148,6 +159,11 @@ public class UserAuthKeyboardInteractive extends AbstractUserAuth {
             }
         }
 
+        if (buffer.available() > 0) {
+            log.warn("processAuthDataRequest({})[{}] {} trailing garbage bytes at end of SSH_MSG_USERAUTH_INFO_REQUEST",
+                    session, service, num, buffer.available());
+            return false;
+        }
         String[] rep = getUserResponses(name, instruction, lang, prompt, echo);
         if (rep == null) {
             if (debugEnabled) {
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/auth/keyboard/UserAuthKeyboardInteractive.java b/sshd-core/src/main/java/org/apache/sshd/server/auth/keyboard/UserAuthKeyboardInteractive.java
index 5022e7e51..0d179a3b4 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/auth/keyboard/UserAuthKeyboardInteractive.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/auth/keyboard/UserAuthKeyboardInteractive.java
@@ -39,6 +39,8 @@ import org.apache.sshd.server.session.ServerSession;
 public class UserAuthKeyboardInteractive extends AbstractUserAuth {
     public static final String NAME = UserAuthKeyboardInteractiveFactory.NAME;
 
+    private int numberOfPrompts = -1;
+
     public UserAuthKeyboardInteractive() {
         super(NAME);
     }
@@ -93,6 +95,7 @@ public class UserAuthKeyboardInteractive extends AbstractUserAuth {
                     challenge.getLanguageTag(), GenericUtils.size(challenge.getPrompts()));
         }
 
+        numberOfPrompts = challenge.getPrompts().size();
         // Prompt for password
         buffer = session.createBuffer(SshConstants.SSH_MSG_USERAUTH_INFO_REQUEST);
         challenge.append(buffer);
@@ -109,10 +112,10 @@ public class UserAuthKeyboardInteractive extends AbstractUserAuth {
         }
 
         int num = buffer.getInt();
-        // Protect against malicious or corrupted packets
-        if ((num < 0) || (num > SshConstants.SSH_REQUIRED_PAYLOAD_PACKET_LENGTH_SUPPORT)) {
-            log.error("doValidateAuthResponse({}@{}) illogical response count: {}", username, session, num);
-            throw new IndexOutOfBoundsException("Illogical response count: " + num);
+        if (num != numberOfPrompts) {
+            // RFC 4256: if the num-responses field does not match the num-prompts field in the request message, the
+            // server MUST send a failure message.
+            return false;
         }
 
         List<String> responses = (num <= 0) ? Collections.emptyList() : new ArrayList<>(num);


(mina-sshd) 04/18: Add a test for multi-authentication

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 5d089237bcc9b6f7a1ca27d6a40dd49dd1df6f1d
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Wed Sep 23 23:54:21 2026 +0200

    Add a test for multi-authentication
    
    Test "publickey,publickey publickey,password" with only one key and one
    password in the client.
---
 .../sshd/client/auth/pubkey/MultiAuthTest.java     | 24 ++++++++++++++++++++++
 1 file changed, 24 insertions(+)

diff --git a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/MultiAuthTest.java b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/MultiAuthTest.java
index dea0b3e84..be6080bb8 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/MultiAuthTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/auth/pubkey/MultiAuthTest.java
@@ -258,6 +258,30 @@ class MultiAuthTest extends BaseTestSupport {
         assertEquals(expected, sb.toString());
     }
 
+    @Test
+    void testConnect6() throws Exception {
+        CoreModuleProperties.AUTH_METHODS.set(sshd, "publickey,publickey publickey,password");
+        StringBuilder sb = new StringBuilder();
+        try (ClientSession session = createClientSession(USER_NAME, client, port)) {
+            session.setKeyIdentityProvider(ctx -> {
+                List<KeyPair> result = new ArrayList<>();
+                result.add(rsaKeyUser);
+                return result;
+            });
+            session.setPasswordIdentityProvider(PasswordIdentityProvider.wrapPasswords(PASSWORD));
+            session.setPublicKeyAuthenticationReporter(new PubkeyReporter(sb));
+            session.setPasswordAuthenticationReporter(new PasswordReporter(sb));
+            session.auth().verify(AUTH_TIMEOUT);
+        } catch (Exception e) {
+            throw new RuntimeException(e.getMessage() + '\n' + sb.toString(), e);
+        }
+        String expected = "publickey TRY RSA rsa-sha2-512\n" //
+                          + "publickey PARTIAL RSA\n" //
+                          + "password TRY pass\n" //
+                          + "password SUCCESS pass\n";
+        assertEquals(expected, sb.toString());
+    }
+
     private static class PubkeyReporter implements PublicKeyAuthenticationReporter {
 
         private final StringBuilder out;


(mina-sshd) 08/18: SCP: limit the protocol line length

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 588d4ee4fe1aca05828911fed7002d93cb9aa8ee
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Fri Sep 18 22:10:03 2026 +0200

    SCP: limit the protocol line length
    
    SCP uses a line-oriented command protocol with LF-terminated lines.
    OpenSSH limits the maximum length of such protocol lines to 2kB.
    Introduce a similar limit, albeit a bit higher since we allow arbitrary
    character encodings, whereas OpenSSH classic SCP is limited to 8-bit
    characters.
    
    The new limit in Apache MINA SSHD is 16kB. If no LF is seen until that
    limit, an IOException is thrown, terminating the SCP command with an
    error exit status.
---
 .../apache/sshd/scp/common/helpers/ScpIoUtils.java | 11 +++
 .../org/apache/sshd/scp/server/ScpCommand.java     |  2 +-
 .../org/apache/sshd/scp/common/ScpIoUtilsTest.java | 88 ++++++++++++++++++++++
 3 files changed, 100 insertions(+), 1 deletion(-)

diff --git a/sshd-scp/src/main/java/org/apache/sshd/scp/common/helpers/ScpIoUtils.java b/sshd-scp/src/main/java/org/apache/sshd/scp/common/helpers/ScpIoUtils.java
index 5c6a61fa5..ec5b479e3 100644
--- a/sshd-scp/src/main/java/org/apache/sshd/scp/common/helpers/ScpIoUtils.java
+++ b/sshd-scp/src/main/java/org/apache/sshd/scp/common/helpers/ScpIoUtils.java
@@ -45,6 +45,14 @@ import org.slf4j.Logger;
  * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
  */
 public final class ScpIoUtils {
+
+    /**
+     * The SCP protocol uses LF-terminated lines. OpenSSH limits this line length to at most 2048 characters / bytes. We
+     * permit UTF-8 encoding for file names, so our buffer should be considerably larger. If we receive a protocol line
+     * longer than this limit, {@link #readLine(InputStream, Charset)} will throw an {@link IOException}.
+     */
+    public static final int MAX_PROTOCOL_LINE_LENGTH = 16 * 1024;
+
     public static final Set<ClientChannelEvent> COMMAND_WAIT_EVENTS
             = Collections.unmodifiableSet(EnumSet.of(ClientChannelEvent.EXIT_STATUS, ClientChannelEvent.CLOSED));
 
@@ -68,6 +76,9 @@ public final class ScpIoUtils {
                     }
                     return null;
                 } else {
+                    if (baos.size() >= MAX_PROTOCOL_LINE_LENGTH) {
+                        throw new IOException("SCP protocol line too long");
+                    }
                     baos.write(c);
                 }
             }
diff --git a/sshd-scp/src/main/java/org/apache/sshd/scp/server/ScpCommand.java b/sshd-scp/src/main/java/org/apache/sshd/scp/server/ScpCommand.java
index b7f8847b6..c782bcd34 100644
--- a/sshd-scp/src/main/java/org/apache/sshd/scp/server/ScpCommand.java
+++ b/sshd-scp/src/main/java/org/apache/sshd/scp/server/ScpCommand.java
@@ -182,7 +182,7 @@ public class ScpCommand extends AbstractFileSystemCommand implements ServerChann
             } else {
                 throw new IOException("Unsupported mode");
             }
-        } catch (IOException e) {
+        } catch (Throwable e) {
             boolean debugEnabled = log.isDebugEnabled();
             try {
                 Integer statusCode = null;
diff --git a/sshd-scp/src/test/java/org/apache/sshd/scp/common/ScpIoUtilsTest.java b/sshd-scp/src/test/java/org/apache/sshd/scp/common/ScpIoUtilsTest.java
new file mode 100644
index 000000000..ed9e8ff7e
--- /dev/null
+++ b/sshd-scp/src/test/java/org/apache/sshd/scp/common/ScpIoUtilsTest.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.sshd.scp.common;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+
+import org.apache.sshd.scp.common.helpers.ScpIoUtils;
+import org.apache.sshd.util.test.JUnitTestSupport;
+import org.junit.jupiter.api.MethodOrderer.MethodName;
+import org.junit.jupiter.api.Tag;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.TestMethodOrder;
+
+/**
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+@TestMethodOrder(MethodName.class)
+@Tag("NoIoTestCase")
+public class ScpIoUtilsTest extends JUnitTestSupport {
+
+    @Test
+    void testProtocolLineLimitExceeded() throws IOException {
+        byte[] longLine = new byte[ScpIoUtils.MAX_PROTOCOL_LINE_LENGTH + 2];
+        for (int i = 0; i < longLine.length; i++) {
+            longLine[i] = 'A';
+        }
+        ByteArrayInputStream bis = new ByteArrayInputStream(longLine);
+        assertThrows(IOException.class, () -> ScpIoUtils.readLine(bis, StandardCharsets.US_ASCII));
+        bis.reset();
+        longLine[longLine.length - 1] = '\n';
+        assertThrows(IOException.class, () -> ScpIoUtils.readLine(bis, StandardCharsets.US_ASCII));
+    }
+
+    @Test
+    void testProtocolLineLimit() throws IOException {
+        byte[] longLine = new byte[ScpIoUtils.MAX_PROTOCOL_LINE_LENGTH + 1];
+        for (int i = 0; i < longLine.length; i++) {
+            longLine[i] = 'A';
+        }
+        longLine[longLine.length - 1] = '\n';
+        ByteArrayInputStream bis = new ByteArrayInputStream(longLine);
+        String s = ScpIoUtils.readLine(bis, StandardCharsets.US_ASCII);
+        assertEquals(ScpIoUtils.MAX_PROTOCOL_LINE_LENGTH, s.length());
+    }
+
+    @Test
+    void testProtocolLineLimitReached() throws IOException {
+        byte[] longLine = new byte[ScpIoUtils.MAX_PROTOCOL_LINE_LENGTH];
+        for (int i = 0; i < longLine.length; i++) {
+            longLine[i] = 'A';
+        }
+        longLine[longLine.length - 1] = '\n';
+        ByteArrayInputStream bis = new ByteArrayInputStream(longLine);
+        String s = ScpIoUtils.readLine(bis, StandardCharsets.US_ASCII);
+        assertEquals(ScpIoUtils.MAX_PROTOCOL_LINE_LENGTH - 1, s.length());
+    }
+
+    @Test
+    void testProtocolLineShort() throws IOException {
+        byte[] longLine = new byte[ScpIoUtils.MAX_PROTOCOL_LINE_LENGTH];
+        for (int i = 0; i < longLine.length; i++) {
+            longLine[i] = 'A';
+        }
+        longLine[42] = '\n';
+        ByteArrayInputStream bis = new ByteArrayInputStream(longLine);
+        String s = ScpIoUtils.readLine(bis, StandardCharsets.US_ASCII);
+        assertEquals(42, s.length());
+    }
+}


(mina-sshd) 17/18: Prepare release documentation

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit daa4002349bffb4b6045c29dd72d1c5df96a0efd
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Sat Sep 26 12:56:28 2026 +0200

    Prepare release documentation
---
 CHANGES.md | 61 +++++++++++++++++++++++++++++++------------------------------
 1 file changed, 31 insertions(+), 30 deletions(-)

diff --git a/CHANGES.md b/CHANGES.md
index a96974787..9a74eb548 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -1,3 +1,33 @@
+# Apache MINA SSHD 2.20.0
+
+Changes since [version 2.19.0](./docs/changes/2.19.0.md):
+
+## Bug Fixes
+
+* [GH-656](https://github.com/apache/mina-sshd/issues/656) `ChannelPipedInputStream`: shrink buffer when emptied
+* [GH-906](https://github.com/apache/mina-sshd/issues/906) Fix finding a signature factory for BC ed25519 keys
+* [GH-911](https://github.com/apache/mina-sshd/issues/911) Fix server-side SOCKS5 proxy for fragmented and pipelined CONNECT requests
+* Allow asynchronous authentication only for password and keyboard-interactive authentication schemes
+* Fix authentication requiring multiple public keys (server-side)
+* Better argument handling in sshd-git
+* More checks in authentication (server-side)
+* Better SCP command handling
+* SFTP client: simplify response message handling
+* Fix check-file-name/check-file-handle SFTP v6 extension (server-side)
+* Improve LDAP authentication (sshd-ldap)
+
+## New Features
+
+* [GH-905](https://github.com/apache/mina-sshd/issues/905) Implement the "from" and "expiry-time" options in `authorized_keys` handling in public key authentication (server side)
+
+## Potential Compatibility Issues
+
+None.
+
+## Major Code Re-factoring
+
+None.
+
 # Previous Versions
 
 * [Version 2.1.0 to 2.2.0](./docs/changes/2.2.0.md)
@@ -24,33 +54,4 @@
 * [Version 2.16.0 to 2.17.0](./docs/changes/2.17.0.md)
 * [Version 2.17.0 to 2.17.1](./docs/changes/2.17.1.md)
 * [Version 2.17.1 to 2.18.0](./docs/changes/2.18.0.md)
-
-# Latest Version
-
-* **[Version 2.18.0 to 2.19.0](./docs/changes/2.19.0.md)**
-
-# Planned for Next Version
-
-## Bug Fixes
-
-* [GH-656](https://github.com/apache/mina-sshd/issues/656) `ChannelPipedInputStream`: shrink buffer when emptied
-* [GH-906](https://github.com/apache/mina-sshd/issues/906) Fix finding a signature factory for BC ed25519 keys
-* [GH-911](https://github.com/apache/mina-sshd/issues/911) Fix server-side SOCKS5 proxy for fragmented and pipelined CONNECT requests
-* Allow asynchronous authentication only for password and keyboard-interactive authentication schemes
-* Fix authentication requiring multiple public keys (server-side)
-* Better argument handling in sshd-git
-* More checks in authentication (server-side)
-* Better SCP command handling
-* Simplify SFTP response message handling
-* Fix check-file-name/check-file-handle SFTP v6 extension
-* Improve LDAP authentication (sshd-ldap)
-
-## New Features
-
-* [GH-905](https://github.com/apache/mina-sshd/issues/905) Implement the "from" and "expiry-time" options in `authorized_keys` handling in public key authentication
-
-## Potential Compatibility Issues
-
-
-## Major Code Re-factoring
-
+* [Version 2.18.0 to 2.19.0](./docs/changes/2.19.0.md)


(mina-sshd) 09/18: DefaultSftpClient: simplify SFTP message handling

Posted by tw...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

tomaswolf pushed a commit to branch rc-2.20.0
in repository https://gitbox.apache.org/repos/asf/mina-sshd.git

commit 53bce94f4b27d1dd7b4d8d730af8b96b9616446f
Author: Thomas Wolf <tw...@apache.org>
AuthorDate: Sat Sep 19 13:07:05 2026 +0200

    DefaultSftpClient: simplify SFTP message handling
    
    Change the way reply reception is handled. When sending a request,
    register a CompletableFuture in the "messges" map, and when the reply
    is received, complete the future with the received buffer.
    
    This has multiple advantages:
    
    * We can detect spurious reply messages without outstanding request.
    * Receiving a reply wakes up only the single thread waiting for it.
    * The code waiting for reply reception is simplified.
---
 .../apache/sshd/common/RuntimeSshException.java    |   2 +-
 .../sshd/sftp/client/impl/DefaultSftpClient.java   | 178 +++++++++++++--------
 2 files changed, 108 insertions(+), 72 deletions(-)

diff --git a/sshd-common/src/main/java/org/apache/sshd/common/RuntimeSshException.java b/sshd-common/src/main/java/org/apache/sshd/common/RuntimeSshException.java
index 8c9164fe6..7d6182b95 100644
--- a/sshd-common/src/main/java/org/apache/sshd/common/RuntimeSshException.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/RuntimeSshException.java
@@ -35,7 +35,7 @@ public class RuntimeSshException extends RuntimeException {
     }
 
     public RuntimeSshException(Throwable cause) {
-        this(null, cause);
+        this(cause.toString(), cause);
     }
 
     public RuntimeSshException(String message, Throwable cause) {
diff --git a/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/DefaultSftpClient.java b/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/DefaultSftpClient.java
index 2771c170b..422dc5b81 100644
--- a/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/DefaultSftpClient.java
+++ b/sshd-sftp/src/main/java/org/apache/sshd/sftp/client/impl/DefaultSftpClient.java
@@ -26,16 +26,20 @@ import java.io.StreamCorruptedException;
 import java.net.SocketTimeoutException;
 import java.nio.charset.Charset;
 import java.time.Duration;
-import java.time.Instant;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
 import java.util.NavigableMap;
 import java.util.Objects;
 import java.util.TreeMap;
+import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.CompletionException;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
@@ -75,7 +79,7 @@ import org.apache.sshd.sftp.server.SftpSubsystemEnvironment;
 public class DefaultSftpClient extends AbstractSftpClient {
     private final ClientSession clientSession;
     private final ChannelSubsystem channel;
-    private final Map<Integer, Buffer> messages = new ConcurrentHashMap<>();
+    private final Map<Integer, CompletableFuture<Buffer>> messages = new ConcurrentHashMap<>();
     private final AtomicInteger cmdId = new AtomicInteger(100);
     private final Buffer receiveBuffer = new ByteArrayBuffer();
     private final AtomicInteger versionHolder = new AtomicInteger(0);
@@ -107,10 +111,8 @@ public class DefaultSftpClient extends AbstractSftpClient {
         Duration initializationTimeout = SftpModuleProperties.SFTP_CHANNEL_OPEN_TIMEOUT.getRequired(clientSession);
         this.channel.open().verify(initializationTimeout);
         this.channel.onClose(() -> {
-            synchronized (messages) {
-                closing.set(true);
-                messages.notifyAll();
-            }
+            closing.set(true);
+            messages.forEach((i, future) -> future.cancel(true));
 
             if (versionHolder.get() <= 0) {
                 log.warn("onClose({}) closed before version negotiated", channel);
@@ -266,10 +268,16 @@ public class DefaultSftpClient extends AbstractSftpClient {
                     getClientChannel(), id, SftpConstants.getCommandMessageName(type), length);
         }
 
-        synchronized (messages) {
-            messages.put(id, buffer);
-            messages.notifyAll();
+        CompletableFuture<Buffer> request = messages.get(id);
+        if (request == null) {
+            throw new IOException("SFTP: received a reply " + SftpConstants.getCommandMessageName(type) //
+                                  + " of length " + length + " for a request never sent; id = " + id);
+        }
+        if (request.isDone()) {
+            throw new IOException("SFTP: received a duplicate reply " + SftpConstants.getCommandMessageName(type)
+                                  + " of length " + length + " for request  id = " + id);
         }
+        request.complete(buffer);
     }
 
     @Override
@@ -320,7 +328,15 @@ public class DefaultSftpClient extends AbstractSftpClient {
             if (msg != null) {
                 msg.waitUntilSent();
             }
-            IoWriteFuture writeFuture = asyncIn.writeBuffer(buf);
+            messages.put(id, new CompletableFuture<>());
+            IoWriteFuture writeFuture = asyncIn.writeBuffer(buf).addListener(future -> {
+                if (!future.isWritten()) {
+                    CompletableFuture<Buffer> reply = messages.remove(id);
+                    if (reply != null) {
+                        reply.cancel(true);
+                    }
+                }
+            });
             Duration sendTimeout = SFTP_CLIENT_CMD_TIMEOUT.getRequired(clientChannel);
             msg = new SftpMessage(id, writeFuture, sendTimeout);
             lastMessage.set(msg);
@@ -350,30 +366,46 @@ public class DefaultSftpClient extends AbstractSftpClient {
 
     @Override
     public Buffer receive(int id, Duration idleTimeout) throws IOException {
-        synchronized (messages) {
-            if (GenericUtils.isPositive(idleTimeout)) {
-                Instant waitUntil = Instant.now().plus(idleTimeout);
-                for (;;) {
-                    if (isClosing() || !isOpen()) {
-                        throw new SshException("Channel is being closed");
-                    }
-                    Buffer buffer = messages.remove(id);
-                    if (buffer != null) {
-                        return buffer;
-                    }
-                    Duration waitFor = Duration.between(Instant.now(), waitUntil);
-                    if (!GenericUtils.isPositive(waitFor)) {
-                        break; // Timeout expired
-                    }
-                    try {
-                        messages.wait(waitFor.toMillis(), waitFor.getNano() % 1_000_000);
-                    } catch (InterruptedException e) {
-                        throw (IOException) new InterruptedIOException("Interrupted while waiting for messages").initCause(e);
-                    }
+        if (!GenericUtils.isPositive(idleTimeout)) {
+            // Immediate check
+            CompletableFuture<Buffer> reply = messages.get(id);
+            if (reply != null && reply.isDone()) {
+                messages.remove(id);
+                try {
+                    return reply.getNow(null);
+                } catch (CancellationException e) {
+                    return null;
+                } catch (CompletionException e) {
+                    // Future was completed exceptionally. Should not occur.
+                    Throwable t = e.getCause();
+                    throw new IOException("Reply for request was terminated exceptionally", t);
                 }
             }
-            // Try one last time.
-            return messages.remove(id);
+            return null;
+        }
+        try {
+            if (isClosing() || !isOpen()) {
+                throw new SshException("Channel is being closed");
+            }
+            CompletableFuture<Buffer> reply = messages.get(id);
+            if (reply == null) {
+                return null;
+            }
+            try {
+                return reply.get(idleTimeout.toNanos(), TimeUnit.NANOSECONDS);
+            } finally {
+                messages.remove(id);
+            }
+        } catch (CancellationException | TimeoutException e) {
+            return null;
+        } catch (ExecutionException e) {
+            // Future was completed exceptionally. Should not occur.
+            Throwable t = e.getCause();
+            throw new IOException("Reply for request was terminated exceptionally", t);
+        } catch (InterruptedException e) {
+            IOException e0 = new InterruptedIOException("Interrupted while waiting for messages");
+            e0.initCause(e);
+            throw e0;
         }
     }
 
@@ -399,13 +431,31 @@ public class DefaultSftpClient extends AbstractSftpClient {
             log.trace("init({}) send SSH_FXP_INIT - initial version={}", clientChannel, initialVersion);
         }
 
-        IoWriteFuture writeFuture = asyncIn.writeBuffer(buf);
-        writeFuture.verify(initializationTimeout);
+        // The initial message from the peer will have the SFTP version number in place of the requestId. So it may
+        // appear in positions 3, 4, 5, or 6 in the map. Hence we have to set our future in all these places.
+        CompletableFuture<Buffer> reply = new CompletableFuture<>();
+        for (int i = 0; i <= SftpConstants.SFTP_V6; i++) {
+            messages.put(i, reply);
+        }
+        IoWriteFuture writeFuture = asyncIn.writeBuffer(buf).addListener(future -> {
+            if (!future.isWritten()) {
+                messages.clear();
+                reply.cancel(true);
+            }
+        });
+        Buffer buffer;
+        try {
+            writeFuture.verify(initializationTimeout);
 
-        if (traceEnabled) {
-            log.trace("init({}) wait for SSH_FXP_INIT respose (timeout={})", clientChannel, initializationTimeout);
+            if (traceEnabled) {
+                log.trace("init({}) wait for SSH_FXP_INIT respose (timeout={})", clientChannel, initializationTimeout);
+            }
+
+            buffer = waitForInitResponse(reply, initializationTimeout);
+        } finally {
+            messages.clear();
         }
-        Buffer buffer = waitForInitResponse(initializationTimeout);
+
         handleInitResponse(buffer);
     }
 
@@ -453,43 +503,29 @@ public class DefaultSftpClient extends AbstractSftpClient {
         }
     }
 
-    protected Buffer waitForInitResponse(Duration initializationTimeout) throws IOException {
+    protected Buffer waitForInitResponse(CompletableFuture<Buffer> reply, Duration initializationTimeout) throws IOException {
         ValidateUtils.checkTrue(GenericUtils.isPositive(initializationTimeout), "Invalid initialization timeout: %d",
-                initializationTimeout);
-
-        synchronized (messages) {
-            /*
-             * We need to use a timeout since if the remote server does not support SFTP, we will not know it
-             * immediately. This is due to the fact that the request for the subsystem does not contain a reply as to
-             * its success or failure. Thus, the SFTP channel is created by the client, but there is no one on the other
-             * side to reply - thus the need for the timeout
-             */
-            Instant now = Instant.now();
-            Instant max = now.plus(initializationTimeout);
-            while ((now.compareTo(max) < 0) && messages.isEmpty() && (!isClosing()) && isOpen()) {
-                try {
-                    Duration rem = Duration.between(now, max);
-                    messages.wait(rem.toMillis(), rem.getNano() % 1_000_000);
-                    now = Instant.now();
-                } catch (InterruptedException e) {
-                    throw (IOException) new InterruptedIOException(
-                            "Interrupted init() while " + Duration.between(now, max) + " remaining").initCause(e);
-                }
-            }
+                initializationTimeout.toMillis());
 
-            if (isClosing() || (!isOpen())) {
+        try {
+            Buffer buffer = reply.get(initializationTimeout.toNanos(), TimeUnit.NANOSECONDS);
+            if (isClosing() || !isOpen()) {
                 throw new EOFException("Closing while await init message");
             }
-
-            if (messages.isEmpty()) {
-                throw new SocketTimeoutException(
-                        "No incoming initialization response received within " + initializationTimeout + " msec.");
-            }
-
-            Collection<Integer> ids = messages.keySet();
-            Iterator<Integer> iter = ids.iterator();
-            Integer reqId = iter.next();
-            return messages.remove(reqId);
+            return buffer;
+        } catch (CancellationException e) {
+            throw new EOFException("Closing while await init message");
+        } catch (TimeoutException e) {
+            throw new SocketTimeoutException(
+                    "No incoming initialization response received within " + initializationTimeout.toMillis() + " msec.");
+        } catch (ExecutionException e) {
+            // Future was completed exceptionally. Should not occur.
+            Throwable t = e.getCause();
+            throw new IOException("Initialization request was terminated exceptionally", t);
+        } catch (InterruptedException e) {
+            IOException e0 = new InterruptedIOException("Interrupted while waiting for initial reply");
+            e0.initCause(e);
+            throw e0;
         }
     }