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

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


The following commit(s) were added to refs/heads/dev_3.0 by this push:
     new 800012232 GH-928: Add pure ML-KEM key-exchange algorithms
800012232 is described below

commit 8000122321a25beeeda5c0530f9c33ae18b61cb4
Author: Thomas Wolf <[email protected]>
AuthorDate: Sat Oct 17 12:32:19 2026 +0200

    GH-928: Add pure ML-KEM key-exchange algorithms
    
    Implement draft-harrison-sshm-mlkm-02[1]; SSH KEX algorithms
    mlkem512-sha256, mlkem768-sha256, and mlkem1024-sha384.
    
    Since the hybrid ML-KEM algorithms were already implemented, this is
    mostly wiring and in DHGClient/Server skipping the hybrid part.
    
    Interoperability tests are run against the OQS fork of OpenSSH in a
    pre-built test container.
    
    [1] https://datatracker.ietf.org/doc/html/draft-harrison-sshm-mlkem-02
---
 CHANGES.md                                         |   4 +
 docs/standards.md                                  |  26 +++--
 .../org/apache/sshd/common/util/security/KEM.java  |   2 +
 .../security/SunJCESecurityProviderRegistrar.java  |   2 +-
 .../security/bouncycastle/BouncyCastleKEM.java     |   4 +-
 .../common/util/security/bouncycastle/MLKEM.java   |  29 ++++-
 .../apache/sshd/common/util/security/JceKEM.java   |  12 +-
 .../java/org/apache/sshd/client/kex/DHGClient.java |  36 ++++--
 .../java/org/apache/sshd/common/BaseBuilder.java   |   4 +
 .../apache/sshd/common/kex/BuiltinDHFactories.java |  72 +++++++++++-
 .../org/apache/sshd/common/kex/BuiltinKEM.java     |   2 +
 .../java/org/apache/sshd/common/kex/KEMOnlyDH.java |  85 ++++++++++++++
 .../java/org/apache/sshd/server/kex/DHGServer.java |  37 ++++--
 .../sshd/client/kex/OqsOpenSshInteropTest.java     | 129 +++++++++++++++++++++
 14 files changed, 403 insertions(+), 41 deletions(-)

diff --git a/CHANGES.md b/CHANGES.md
index 6afafd888..6d1a9827f 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -68,3 +68,7 @@ Merges 2.20.1 into the 3.0.0 stream, bringing in two bug 
fixes; one a regression
 
 
 ## New Features
+
+* Pure ML-KEM key exchanges `mlkem512-sha256`, `mlkem768-sha256`, 
`mlkem1024-sha384` if Bouncy Castle is present or if running on Java >= 24.
+    * Implements IETF RFC draft 
[draft-harrison-sshm-mlkem-02](https://datatracker.ietf.org/doc/draft-harrison-sshm-mlkem/02/),
 "Module-Lattice Key Exchange in SSH"
+
diff --git a/docs/standards.md b/docs/standards.md
index 88e739980..fed634ccf 100644
--- a/docs/standards.md
+++ b/docs/standards.md
@@ -30,7 +30,8 @@
 * [RFC 8731 - Secure Shell (SSH) Key Exchange Method Using Curve25519 and 
Curve448](https://tools.ietf.org/html/rfc8731)
 * [Key Exchange (KEX) Method Updates and Recommendations for Secure 
Shell](https://tools.ietf.org/html/draft-ietf-curdle-ssh-kex-sha2-03)
 * [Secure Shell (SSH) Key Exchange Method Using Hybrid Streamlined NTRU Prime 
sntrup761 and X25519 with SHA-512: 
sntrup761x25519-sha512](https://www.ietf.org/archive/id/draft-josefsson-ntruprime-ssh-02.html)
-* [PQ/T Hybrid Key Exchange in 
SSH](https://datatracker.ietf.org/doc/html/draft-kampanakis-curdle-ssh-pq-ke-04)
+* [RFC 10042 - Post-Quantum/Traditional Hybrid Key Exchange with the 
Module-Lattice-Based Key-Encapsulation Mechanism for Use in 
SSH](https://www.rfc-editor.org/info/rfc10042/)
+* [Module-Lattice Key Exchange in 
SSH](https://datatracker.ietf.org/doc/html/draft-harrison-sshm-mlkem-02)
 
 ### OpenSSH
 
@@ -95,16 +96,21 @@ aes128-gcm@<!-- -->openssh.com, aes256-gcm@<!-- 
-->openssh.com, chacha20-poly130
 
 ### Key exchange
 
+Traditional key exchanges:
+
 * diffie-hellman-group1-sha1, diffie-hellman-group-exchange-sha256, 
diffie-hellman-group14-sha1, diffie-hellman-group14-sha256
 , diffie-hellman-group15-sha512, diffie-hellman-group16-sha512, 
diffie-hellman-group17-sha512, diffie-hellman-group18-sha512
-, ecdh-sha2-nistp256, ecdh-sha2-nistp384, ecdh-sha2-nistp521, 
curve25519-sha256, curve25519-sha256@<!-- -->libssh.org, curve448-sha512
-    * On Java versions before Java 11, [Bouncy 
Castle](./dependencies.md#bouncy-castle) is required for curve25519-sha256, 
curve25519-sha256@<!-- -->libssh.org, or curve448-sha512.
+* ecdh-sha2-nistp256, ecdh-sha2-nistp384, ecdh-sha2-nistp521
+* curve25519-sha256, curve25519-sha256@<!-- -->libssh.org, curve448-sha512 if 
[Bouncy Castle](./dependencies.md#bouncy-castle) is present or running on Java 
>= 11.
+
+Post-quantum hybrid key exchanges (combining a post-quantum and a traditional 
KEX):
+
+* sntrup761x25519-sha512, sntrup761x25519-sha512@<!-- -->openssh.com if 
[Bouncy Castle](./dependencies.md#bouncy-castle) is present.
+* mlkem768x25519-sha256, mlkem768nistp256-sha256, and mlkem1024nistp384-sha384 
if [Bouncy Castle](./dependencies.md#bouncy-castle) is present or running on 
Java >= 24.
 
-* If [Bouncy Castle](./dependencies.md#bouncy-castle) is present, the 
following post-quantum cryptography (PQC) hybrid key
-  exchanges are also supported: sntrup761x25519-sha512, 
sntrup761x25519-sha512@<!-- -->openssh.com, mlkem768x25519-sha256,
-  mlkem768nistp256-sha256, and mlkem1024nistp384-sha384.
+Post-quantum pure key exchanges:
 
-* The three ML-KEM algorithms are also supported on Java >= 24 without Bouncy 
Castle. 
+* mlkem512-sha256, mlkem768-sha256, mlkem1024-sha384 if [Bouncy 
Castle](./dependencies.md#bouncy-castle) is present or running on Java >= 24.
 
 ### Compressions
 
@@ -117,9 +123,9 @@ aes128-gcm@<!-- -->openssh.com, aes256-gcm@<!-- 
-->openssh.com, chacha20-poly130
 , ssh-rsa-cert-v01@<!-- -->openssh.com, ssh-dss-cert-v01<!-- -->@openssh.com, 
ssh-ed25519-cert-v01@<!-- -->openssh.com
 , ecdsa-sha2-nistp256-cert-v01@<!-- -->openssh.com, 
ecdsa-sha2-nistp384-cert-v01<!-- -->@openssh.com
 , ecdsa-sha2-nistp521-cert-v01<!-- -->@openssh.com
-    * On Java versions before Java 15, ed25519 keys are supported if Bouncy 
Castle or the optional `net.i2p.crypto.eddsa` dependency
-      are present. If both are present, `net.i2p.crypto.eddsa` is used. On 
Java >= 15, ed25519 keys are supported using the JDK
-      implementation.
+    * On Java versions before Java 15, ed25519 keys are supported if [Bouncy 
Castle](./dependencies.md#bouncy-castle) or the 
+      optional `net.i2p.crypto.eddsa` dependency are present. If both are 
present, `net.i2p.crypto.eddsa` is used. On Java >= 15,
+      ed25519 keys are supported using the JDK implementation.
 
 **Note:** The above list contains all the supported security settings in the 
code. However, in accordance with the latest recommendations
 the default client/server setup includes only the security settings that are 
currently considered safe to use. Users who wish to include
diff --git 
a/sshd-common/src/main/java/org/apache/sshd/common/util/security/KEM.java 
b/sshd-common/src/main/java/org/apache/sshd/common/util/security/KEM.java
index 10f176655..b71633c35 100644
--- a/sshd-common/src/main/java/org/apache/sshd/common/util/security/KEM.java
+++ b/sshd-common/src/main/java/org/apache/sshd/common/util/security/KEM.java
@@ -25,6 +25,8 @@ import org.apache.sshd.common.OptionalFeature;
  */
 public interface KEM extends OptionalFeature {
 
+    String ML_KEM_512 = "ML-KEM-512";
+
     String ML_KEM_768 = "ML-KEM-768";
 
     String ML_KEM_1024 = "ML-KEM-1024";
diff --git 
a/sshd-common/src/main/java/org/apache/sshd/common/util/security/SunJCESecurityProviderRegistrar.java
 
b/sshd-common/src/main/java/org/apache/sshd/common/util/security/SunJCESecurityProviderRegistrar.java
index 91d236bfd..a5b90012c 100644
--- 
a/sshd-common/src/main/java/org/apache/sshd/common/util/security/SunJCESecurityProviderRegistrar.java
+++ 
b/sshd-common/src/main/java/org/apache/sshd/common/util/security/SunJCESecurityProviderRegistrar.java
@@ -62,7 +62,7 @@ public class SunJCESecurityProviderRegistrar extends 
AbstractSecurityProviderReg
         defaultProperties.put(baseName + ".Mac", 
"HmacSha1,HmacSha224,HmacSha256,HmacSha384,HmacSha512");
         if (isSupported()) {
             if (haveKEM(getSecurityProvider())) {
-                String kems = KEM.ML_KEM_1024 + ',' + KEM.ML_KEM_768;
+                String kems = KEM.ML_KEM_1024 + ',' + KEM.ML_KEM_768 + ',' + 
KEM.ML_KEM_512;
                 defaultProperties.put(baseName + ".KEM", kems);
                 defaultProperties.put(baseName + ".KeyPairGenerator", kems);
                 defaultProperties.put(baseName + ".KeyFactory", kems);
diff --git 
a/sshd-common/src/main/java/org/apache/sshd/common/util/security/bouncycastle/BouncyCastleKEM.java
 
b/sshd-common/src/main/java/org/apache/sshd/common/util/security/bouncycastle/BouncyCastleKEM.java
index bb83d4e14..47594446b 100644
--- 
a/sshd-common/src/main/java/org/apache/sshd/common/util/security/bouncycastle/BouncyCastleKEM.java
+++ 
b/sshd-common/src/main/java/org/apache/sshd/common/util/security/bouncycastle/BouncyCastleKEM.java
@@ -30,7 +30,9 @@ enum BouncyCastleKEM implements KEMFactory {
 
     @Override
     public KEM get(String algorithm, Provider provider) throws 
NoSuchAlgorithmException {
-        if (KEM.ML_KEM_768.equalsIgnoreCase(algorithm)) {
+        if (KEM.ML_KEM_512.equalsIgnoreCase(algorithm)) {
+            return MLKEM.ML_KEM_512;
+        } else if (KEM.ML_KEM_768.equalsIgnoreCase(algorithm)) {
             return MLKEM.ML_KEM_768;
         } else if (KEM.ML_KEM_1024.equalsIgnoreCase(algorithm)) {
             return MLKEM.ML_KEM_1024;
diff --git 
a/sshd-common/src/main/java/org/apache/sshd/common/util/security/bouncycastle/MLKEM.java
 
b/sshd-common/src/main/java/org/apache/sshd/common/util/security/bouncycastle/MLKEM.java
index a05ce2920..5524d7c45 100644
--- 
a/sshd-common/src/main/java/org/apache/sshd/common/util/security/bouncycastle/MLKEM.java
+++ 
b/sshd-common/src/main/java/org/apache/sshd/common/util/security/bouncycastle/MLKEM.java
@@ -35,8 +35,8 @@ import 
org.bouncycastle.crypto.params.MLKEMPrivateKeyParameters;
 import org.bouncycastle.crypto.params.MLKEMPublicKeyParameters;
 
 /**
- * An implementation of the mlkem768 key encapsulation method (KEM), formerly 
known as Kyber, using Bouncy Castle. But
- * see appendix C of FIPS 203 ("Differences From the CRYSTALS-Kyber 
Submission").
+ * An implementation of the ML-KEM key encapsulation method (KEM), formerly 
known as Kyber, using Bouncy Castle. But see
+ * appendix C of FIPS 203 ("Differences From the CRYSTALS-Kyber Submission").
  * <p>
  * NIST specifies that they removed a hash in the encapsulation/decapsulation 
methods.
  * </p>
@@ -45,6 +45,24 @@ import 
org.bouncycastle.crypto.params.MLKEMPublicKeyParameters;
  */
 enum MLKEM implements KEM {
 
+    ML_KEM_512 {
+
+        @Override
+        public Client getClient() {
+            return new Client(Parameters.mlkem512);
+        }
+
+        @Override
+        public Server getServer() {
+            return new Server(Parameters.mlkem512);
+        }
+
+        @Override
+        public boolean isSupported() {
+            return Parameters.mlkem512.isSupported();
+        }
+    },
+
     ML_KEM_768 {
 
         @Override
@@ -84,6 +102,13 @@ enum MLKEM implements KEM {
     enum Parameters implements OptionalFeature {
         // For key sizes see NIST FIPS 203, section 8, table 3. Bouncy Castle 
does not expose the
         // public key sizes through its API. (Though they compute them 
internally.)
+        mlkem512(800) {
+
+            @Override
+            Object getMLKEMParameters() {
+                return MLKEMParameters.ml_kem_512;
+            }
+        },
         mlkem768(1184) {
 
             @Override
diff --git 
a/sshd-common/src/main/java24/org/apache/sshd/common/util/security/JceKEM.java 
b/sshd-common/src/main/java24/org/apache/sshd/common/util/security/JceKEM.java
index 721ba8dcf..d4146c944 100644
--- 
a/sshd-common/src/main/java24/org/apache/sshd/common/util/security/JceKEM.java
+++ 
b/sshd-common/src/main/java24/org/apache/sshd/common/util/security/JceKEM.java
@@ -39,6 +39,10 @@ enum JceKEM implements KEMFactory {
 
     // See 
https://datatracker.ietf.org/doc/html/draft-ietf-lamps-kyber-certificates-11
 
+    // Sequence, length 818 (3 bytes), Sequence, length 11, OID, length 9, 9 
bytes OID, Bit String, length 801 (3
+    // bytes), zero unused bits. OID = 2.16.840.101.3.4.4.1
+    private static final byte[] ML512_X509_PREFIX = { 0x30, (byte) 0x82, 0x03, 
(byte) 0x32, 0x30, 0x0b, 0x06, 0x09, 0x60,
+            (byte) 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x04, 0x01, 0x03, 
(byte) 0x82, 0x03, 0x21, 0x00 };
     // Sequence, length 1202 (3 bytes), Sequence, length 11, OID, length 9, 9 
bytes OID, Bit String, length 1185 (3
     // bytes), zero unused bits. OID = 2.16.840.101.3.4.4.2
     private static final byte[] ML768_X509_PREFIX = { 0x30, (byte) 0x82, 0x04, 
(byte) 0xb2, 0x30, 0x0b, 0x06, 0x09, 0x60,
@@ -53,7 +57,9 @@ enum JceKEM implements KEMFactory {
         javax.crypto.KEM kem = provider == null
                 ? javax.crypto.KEM.getInstance(algorithm)
                 : javax.crypto.KEM.getInstance(algorithm, provider);
-        if (KEM.ML_KEM_768.equalsIgnoreCase(algorithm)) {
+        if (KEM.ML_KEM_512.equalsIgnoreCase(algorithm)) {
+            return new KEMWrapper(kem, KEM.ML_KEM_512, provider, 800, 768, 
ML512_X509_PREFIX);
+        } else if (KEM.ML_KEM_768.equalsIgnoreCase(algorithm)) {
             return new KEMWrapper(kem, KEM.ML_KEM_768, provider, 1184, 1088, 
ML768_X509_PREFIX);
         } else if (KEM.ML_KEM_1024.equalsIgnoreCase(algorithm)) {
             return new KEMWrapper(kem, KEM.ML_KEM_1024, provider, 1568, 1568, 
ML1024_X509_PREFIX);
@@ -63,7 +69,9 @@ enum JceKEM implements KEMFactory {
 
     @Override
     public boolean isSupported(String algorithm) {
-        if (KEM.ML_KEM_768.equalsIgnoreCase(algorithm) || 
KEM.ML_KEM_1024.equalsIgnoreCase(algorithm)) {
+        if (KEM.ML_KEM_512.equalsIgnoreCase(algorithm)
+                || KEM.ML_KEM_768.equalsIgnoreCase(algorithm)
+                || KEM.ML_KEM_1024.equalsIgnoreCase(algorithm)) {
             try {
                 return javax.crypto.KEM.getInstance(algorithm) != null;
             } catch (NoSuchAlgorithmException e) {
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/kex/DHGClient.java 
b/sshd-core/src/main/java/org/apache/sshd/client/kex/DHGClient.java
index 3649d986d..924d8cc9e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/kex/DHGClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/kex/DHGClient.java
@@ -37,6 +37,7 @@ import org.apache.sshd.common.digest.Digest;
 import org.apache.sshd.common.kex.AbstractDH;
 import org.apache.sshd.common.kex.CurveSizeIndicator;
 import org.apache.sshd.common.kex.DHFactory;
+import org.apache.sshd.common.kex.KEMOnlyDH;
 import org.apache.sshd.common.kex.KexProposalOption;
 import org.apache.sshd.common.kex.KeyExchange;
 import org.apache.sshd.common.kex.KeyExchangeFactory;
@@ -110,10 +111,12 @@ public class DHGClient extends 
AbstractDHClientKeyExchange {
             kemClient = kem.getClient();
             kemClient.init();
             e = kemClient.getPublicKey();
-            byte[] dhE = dh.getE();
-            int l = e.length;
-            e = Arrays.copyOf(e, l + dhE.length);
-            System.arraycopy(dhE, 0, e, l, dhE.length);
+            if (!(dh instanceof KEMOnlyDH)) {
+                byte[] dhE = dh.getE();
+                int l = e.length;
+                e = Arrays.copyOf(e, l + dhE.length);
+                System.arraycopy(dhE, 0, e, l, dhE.length);
+            }
             e = updateE(e);
         }
 
@@ -161,16 +164,31 @@ public class DHGClient extends 
AbstractDHClientKeyExchange {
                         throw new 
SshException(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED,
                                 "Wrong F length (should be " + expectedLength 
+ " bytes): " + f.length);
                     }
+                } else if (dh instanceof KEMOnlyDH) {
+                    if (f.length != l) {
+                        throw new 
SshException(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED,
+                                "Wrong F length (should be " + l + " bytes): " 
+ f.length);
+                    }
                 } else if (f.length <= l) {
                     throw new 
SshException(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED,
                             "Strange F length: " + f.length + "  <= " + l);
                 }
                 dh.setF(Arrays.copyOfRange(f, l, f.length));
-                Digest keyHash = dh.getHash();
-                keyHash.init();
-                keyHash.update(kemClient.extractSecret(Arrays.copyOf(f, l)));
-                keyHash.update(dh.getK());
-                k = keyHash.digest();
+                if (dh instanceof KEMOnlyDH) {
+                    k = kemClient.extractSecret(f);
+                    // 
https://datatracker.ietf.org/doc/html/draft-harrison-sshm-mlkem-02 states "K_PQ 
is encoded as
+                    // mpint [RFC4251]". We treat is as a byte array, and 
apparently so does oqs-openssh.
+                    // Interoperability with oqs-openssh is given irrespective 
of the value of the high bit of K (k[0] &
+                    // 0x80). As an mpint one would be supposed to add a zero 
byte in front if the high bit is set (k =
+                    // normalize(k)), but that doesn't add any value to the 
key exchange security and would not interop
+                    // with oqs-openssh.
+                } else {
+                    Digest keyHash = dh.getHash();
+                    keyHash.init();
+                    keyHash.update(kemClient.extractSecret(Arrays.copyOf(f, 
l)));
+                    keyHash.update(dh.getK());
+                    k = keyHash.digest();
+                }
             } catch (IllegalArgumentException ex) {
                 log.error("Key encapsulation error", ex);
                 throw new 
SshException(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED,
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/BaseBuilder.java 
b/sshd-core/src/main/java/org/apache/sshd/common/BaseBuilder.java
index 03707b1f5..e64449996 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/BaseBuilder.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/BaseBuilder.java
@@ -92,6 +92,10 @@ public class BaseBuilder<T extends AbstractFactoryManager, S 
extends BaseBuilder
                     BuiltinDHFactories.sntrup761x25519_openssh,
                     BuiltinDHFactories.mlkem1024nistp384,
                     BuiltinDHFactories.mlkem768nistp256,
+                    BuiltinDHFactories.mlkem1024,
+                    BuiltinDHFactories.mlkem768,
+                    BuiltinDHFactories.mlkem512,
+
                     BuiltinDHFactories.curve25519,
                     BuiltinDHFactories.curve25519_libssh,
                     BuiltinDHFactories.curve448,
diff --git 
a/sshd-core/src/main/java/org/apache/sshd/common/kex/BuiltinDHFactories.java 
b/sshd-core/src/main/java/org/apache/sshd/common/kex/BuiltinDHFactories.java
index fd2209d71..965e99aaf 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/kex/BuiltinDHFactories.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/kex/BuiltinDHFactories.java
@@ -304,8 +304,8 @@ public enum BuiltinDHFactories implements DHFactory {
         }
     },
     /**
-     * @see <a href= 
"https://datatracker.ietf.org/doc/html/draft-kampanakis-curdle-ssh-pq-ke-04";>PQ/T
 Hybrid Key
-     *      Exchange in SSH</a>
+     * @see <a href= "https://datatracker.ietf.org/doc/rfc10042/";>RFC 10042: 
Post-Quantum/Traditional Hybrid Key
+     *      Exchange with the Module-Lattice-Based Key-Encapsulation Mechanism 
for Use in SSH</a>
      */
     mlkem768x25519(Constants.MLKEM768_25519_SHA256) {
         @Override
@@ -334,8 +334,8 @@ public enum BuiltinDHFactories implements DHFactory {
         }
     },
     /**
-     * @see <a href= 
"https://datatracker.ietf.org/doc/html/draft-kampanakis-curdle-ssh-pq-ke-04";>PQ/T
 Hybrid Key
-     *      Exchange in SSH</a>
+     * @see <a href= "https://datatracker.ietf.org/doc/rfc10042/";>RFC 10042: 
Post-Quantum/Traditional Hybrid Key
+     *      Exchange with the Module-Lattice-Based Key-Encapsulation Mechanism 
for Use in SSH</a>
      */
     mlkem768nistp256(Constants.MLKEM768_NISTP256_SHA256) {
         @Override
@@ -359,8 +359,8 @@ public enum BuiltinDHFactories implements DHFactory {
         }
     },
     /**
-     * @see <a href= 
"https://datatracker.ietf.org/doc/html/draft-kampanakis-curdle-ssh-pq-ke-04";>PQ/T
 Hybrid Key
-     *      Exchange in SSH</a>
+     * @see <a href= "https://datatracker.ietf.org/doc/rfc10042/";>RFC 10042: 
Post-Quantum/Traditional Hybrid Key
+     *      Exchange with the Module-Lattice-Based Key-Encapsulation Mechanism 
for Use in SSH</a>
      */
     mlkem1024nistp384(Constants.MLKEM1024_NISTP384_SHA384) {
         @Override
@@ -383,6 +383,63 @@ public enum BuiltinDHFactories implements DHFactory {
             return ECCurves.nistp384.isSupported() && 
BuiltinKEM.mlkem1024.isSupported();
         }
     },
+    /**
+     * @see <a href= 
"https://datatracker.ietf.org/doc/draft-harrison-sshm-mlkem/";>Module-Lattice 
Key Exchange in
+     *      SSH</a>
+     */
+    mlkem512(Constants.MLKEM512_SHA256) {
+        @Override
+        public KEMOnlyDH create(Object... params) throws Exception {
+            if (!GenericUtils.isEmpty(params)) {
+                throw new IllegalArgumentException("No accepted parameters for 
" + getName());
+            }
+            return new KEMOnlyDH(BuiltinKEM.mlkem512, BuiltinDigests.sha256);
+        }
+
+        @Override
+        public boolean isSupported() {
+            return BuiltinDigests.sha256.isSupported() && 
BuiltinKEM.mlkem512.isSupported();
+        }
+
+    },
+    /**
+     * @see <a href= 
"https://datatracker.ietf.org/doc/draft-harrison-sshm-mlkem/";>Module-Lattice 
Key Exchange in
+     *      SSH</a>
+     */
+    mlkem768(Constants.MLKEM768_SHA256) {
+        @Override
+        public KEMOnlyDH create(Object... params) throws Exception {
+            if (!GenericUtils.isEmpty(params)) {
+                throw new IllegalArgumentException("No accepted parameters for 
" + getName());
+            }
+            return new KEMOnlyDH(BuiltinKEM.mlkem768, BuiltinDigests.sha256);
+        }
+
+        @Override
+        public boolean isSupported() {
+            return BuiltinDigests.sha256.isSupported() && 
BuiltinKEM.mlkem768.isSupported();
+        }
+
+    },
+    /**
+     * @see <a href= 
"https://datatracker.ietf.org/doc/draft-harrison-sshm-mlkem/";>Module-Lattice 
Key Exchange in
+     *      SSH</a>
+     */
+    mlkem1024(Constants.MLKEM1024_SHA384) {
+        @Override
+        public KEMOnlyDH create(Object... params) throws Exception {
+            if (!GenericUtils.isEmpty(params)) {
+                throw new IllegalArgumentException("No accepted parameters for 
" + getName());
+            }
+            return new KEMOnlyDH(BuiltinKEM.mlkem1024, BuiltinDigests.sha384);
+        }
+
+        @Override
+        public boolean isSupported() {
+            return BuiltinDigests.sha384.isSupported() && 
BuiltinKEM.mlkem1024.isSupported();
+        }
+
+    },
     /**
      * @see <a href=
      *      
"https://www.ietf.org/archive/id/draft-josefsson-ntruprime-ssh-02.html";>draft-josefsson-ntruprime-ssh-02.html</a>
@@ -605,8 +662,11 @@ public enum BuiltinDHFactories implements DHFactory {
         public static final String CURVE25519_SHA256 = "curve25519-sha256";
         public static final String CURVE25519_SHA256_LIBSSH = 
CURVE25519_SHA256 + "@libssh.org";
         public static final String CURVE448_SHA512 = "curve448-sha512";
+        public static final String MLKEM512_SHA256 = "mlkem512-sha256";
+        public static final String MLKEM768_SHA256 = "mlkem768-sha256";
         public static final String MLKEM768_25519_SHA256 = 
"mlkem768x25519-sha256";
         public static final String MLKEM768_NISTP256_SHA256 = 
"mlkem768nistp256-sha256";
+        public static final String MLKEM1024_SHA384 = "mlkem1024-sha384";
         public static final String MLKEM1024_NISTP384_SHA384 = 
"mlkem1024nistp384-sha384";
         public static final String SNTRUP761_25519_SHA512 = 
"sntrup761x25519-sha512";
         public static final String SNTRUP761_25519_SHA512_OPENSSH = 
SNTRUP761_25519_SHA512 + "@openssh.com";
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/kex/BuiltinKEM.java 
b/sshd-core/src/main/java/org/apache/sshd/common/kex/BuiltinKEM.java
index 5beab1763..a8e0e81cb 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/kex/BuiltinKEM.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/kex/BuiltinKEM.java
@@ -30,6 +30,8 @@ import org.apache.sshd.common.util.security.SecurityUtils;
  */
 public enum BuiltinKEM implements KEM, NamedResource, OptionalFeature {
 
+    mlkem512("mlkem512", KEM.ML_KEM_512),
+
     mlkem768("mlkem768", KEM.ML_KEM_768),
 
     mlkem1024("mlkem1024", KEM.ML_KEM_1024),
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/kex/KEMOnlyDH.java 
b/sshd-core/src/main/java/org/apache/sshd/common/kex/KEMOnlyDH.java
new file mode 100644
index 000000000..d4d27a882
--- /dev/null
+++ b/sshd-core/src/main/java/org/apache/sshd/common/kex/KEMOnlyDH.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.common.kex;
+
+import java.util.Objects;
+
+import org.apache.sshd.common.digest.Digest;
+import org.apache.sshd.common.digest.DigestFactory;
+import org.apache.sshd.common.util.buffer.Buffer;
+import org.apache.sshd.common.util.security.KEM;
+
+/**
+ * A "fake" DH that serves only as a transport object for a {@link 
KeyEncapsulationMethod} to implement pure PQ key
+ * exchange in DHGClient and DHGServer.
+ */
+public class KEMOnlyDH extends AbstractDH {
+
+    protected final KEM kem;
+
+    protected final DigestFactory digest;
+
+    public KEMOnlyDH(KEM kem, DigestFactory factory) {
+        this.kem = Objects.requireNonNull(kem, "A KEM is required");
+        this.digest = Objects.requireNonNull(factory, "A DigestFactory is 
required");
+    }
+
+    @Override
+    public KEM getKeyEncapsulation() {
+        return kem;
+    }
+
+    @Override
+    public Digest getHash() throws Exception {
+        return digest.create();
+    }
+
+    @Override
+    public void setF(byte[] f) {
+        // Nothing
+    }
+
+    @Override
+    public byte[] getE() throws Exception {
+        throw new UnsupportedOperationException("KEM key exchange has no E; in 
DHGClient e = kemClient.getPublicKey()");
+    }
+
+    @Override
+    protected byte[] calculateE() throws Exception {
+        return null;
+    }
+
+    @Override
+    protected byte[] calculateK() throws Exception {
+        return null;
+    }
+
+    @Override
+    public void putE(Buffer buffer, byte[] e) {
+        // RFC 10042: plain KEM public key is just a byte sequence
+        buffer.putBytes(e);
+    }
+
+    @Override
+    public void putF(Buffer buffer, byte[] f) {
+        // RFC 10042: KEM server data is just a byte sequence
+        buffer.putBytes(f);
+    }
+
+}
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/kex/DHGServer.java 
b/sshd-core/src/main/java/org/apache/sshd/server/kex/DHGServer.java
index 33d260b49..38c22e714 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/kex/DHGServer.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/kex/DHGServer.java
@@ -29,6 +29,7 @@ import org.apache.sshd.common.digest.Digest;
 import org.apache.sshd.common.kex.AbstractDH;
 import org.apache.sshd.common.kex.CurveSizeIndicator;
 import org.apache.sshd.common.kex.DHFactory;
+import org.apache.sshd.common.kex.KEMOnlyDH;
 import org.apache.sshd.common.kex.KexProposalOption;
 import org.apache.sshd.common.kex.KeyExchange;
 import org.apache.sshd.common.kex.KeyExchangeFactory;
@@ -86,7 +87,9 @@ public class DHGServer extends AbstractDHServerKeyExchange {
         dh = factory.create();
         hash = dh.getHash();
         hash.init();
-        setF(dh.getE());
+        if (!(dh instanceof KEMOnlyDH)) {
+            setF(dh.getE());
+        }
     }
 
     @Override
@@ -117,6 +120,12 @@ public class DHGServer extends AbstractDHServerKeyExchange 
{
                         throw new 
SshException(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED,
                                 "Wrong E length (should be " + expectedLength 
+ " bytes): " + e.length);
                     }
+                } else if (dh instanceof KEMOnlyDH) {
+                    int expectedLength = kemServer.getPublicKeyLength();
+                    if (e.length != expectedLength) {
+                        throw new 
SshException(SshConstants.SSH2_DISCONNECT_KEY_EXCHANGE_FAILED,
+                                "Wrong E length (should be " + expectedLength 
+ " bytes): " + e.length);
+                    }
                 } else {
                     int minLength = kemServer.getPublicKeyLength();
                     if (e.length <= minLength) {
@@ -125,16 +134,24 @@ public class DHGServer extends 
AbstractDHServerKeyExchange {
                     }
                 }
                 dh.setF(kemServer.init(e));
-                byte[] dhK = dh.getK();
-                Digest keyHash = dh.getHash();
-                keyHash.init();
-                keyHash.update(kemServer.getSecret());
-                keyHash.update(dhK);
-                k = keyHash.digest();
+                if (dh instanceof KEMOnlyDH) {
+                    k = kemServer.getSecret();
+                    // 
https://datatracker.ietf.org/doc/html/draft-harrison-sshm-mlkem-02 states "K_PQ 
is encoded as
+                    // mpint [RFC4251]". We treat is as a byte array, and 
apparently so does oqs-openssh.
+                } else {
+                    byte[] dhK = dh.getK();
+                    Digest keyHash = dh.getHash();
+                    keyHash.init();
+                    keyHash.update(kemServer.getSecret());
+                    keyHash.update(dhK);
+                    k = keyHash.digest();
+                }
                 byte[] newF = kemServer.getEncapsulation();
-                int l = newF.length;
-                newF = Arrays.copyOf(newF, l + dh.getE().length);
-                System.arraycopy(dh.getE(), 0, newF, l, dh.getE().length);
+                if (!(dh instanceof KEMOnlyDH)) {
+                    int l = newF.length;
+                    newF = Arrays.copyOf(newF, l + dh.getE().length);
+                    System.arraycopy(dh.getE(), 0, newF, l, dh.getE().length);
+                }
                 setF(newF);
             } catch (IllegalArgumentException ex) {
                 log.error("Key encapsulation error", ex);
diff --git 
a/sshd-test/src/test/java/org/apache/sshd/client/kex/OqsOpenSshInteropTest.java 
b/sshd-test/src/test/java/org/apache/sshd/client/kex/OqsOpenSshInteropTest.java
new file mode 100644
index 000000000..35937e2ab
--- /dev/null
+++ 
b/sshd-test/src/test/java/org/apache/sshd/client/kex/OqsOpenSshInteropTest.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.sshd.client.kex;
+
+import java.net.UnknownHostException;
+import java.time.Duration;
+import java.util.Collections;
+import java.util.Locale;
+
+import org.apache.sshd.AbstractContainerTestBase;
+import org.apache.sshd.client.ClientBuilder;
+import org.apache.sshd.client.SshClient;
+import org.apache.sshd.client.session.ClientSession;
+import org.apache.sshd.common.kex.BuiltinDHFactories;
+import org.apache.sshd.common.kex.DHFactory;
+import org.apache.sshd.common.kex.KexProposalOption;
+import org.apache.sshd.common.signature.BuiltinSignatures;
+import org.junit.jupiter.api.Assumptions;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.testcontainers.containers.ContainerFetchException;
+import org.testcontainers.containers.ContainerLaunchException;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.output.Slf4jLogConsumer;
+import org.testcontainers.containers.wait.strategy.Wait;
+import org.testcontainers.utility.DockerImageName;
+
+/**
+ * Tests interoperability with the prebuilt OQS-OpenSSH image.
+ *
+ * @author <a href="mailto:[email protected]";>Apache MINA SSHD Project</a>
+ */
+class OqsOpenSshInteropTest extends AbstractContainerTestBase {
+
+    private static final Logger LOG = 
LoggerFactory.getLogger(OqsOpenSshInteropTest.class);
+
+    // Use the SHA of the multi-arch image
+    private static final String OQS_OPENSSH_IMAGE
+            = 
"ghcr.io/apache/mina-sshd-oqs-openssh:dev@sha256:b422cf129003bba8bd712812bb303ad1440fb34de64a219148db581660d8d243";
+
+    @Test
+    void hybridConnectivity() throws Exception {
+        // Control to verify the container works
+        DHFactory factory = BuiltinDHFactories.mlkem768x25519;
+        Assumptions.assumeTrue(factory.isSupported(), "Hybrid ML-KEM is not 
supported by this provider");
+        connect(factory);
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = { "mlkem512-sha256", "mlkem768-sha256", 
"mlkem1024-sha384" })
+    void pureMlKem768(String kexName) throws Exception {
+        DHFactory factory = BuiltinDHFactories.fromFactoryName(kexName);
+        assertNotNull(factory, "Factory should exist");
+        Assumptions.assumeTrue(factory.isSupported(), "Pure ML-KEM " + kexName 
+ " is not supported by this provider");
+        connect(factory);
+    }
+
+    private static boolean isImageUnavailable(Throwable error) {
+        for (Throwable cause = error; cause != null; cause = cause.getCause()) 
{
+            if (cause instanceof ContainerFetchException || cause instanceof 
UnknownHostException) {
+                return true;
+            }
+            String message = cause.getMessage();
+            if (message != null) {
+                message = message.toLowerCase(Locale.ROOT);
+                if (message.contains("manifest unknown") || 
message.contains("pull access denied")
+                        || message.contains("unauthorized") || 
message.contains("authentication required")) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    private void connect(DHFactory factory) throws Exception {
+        Assumptions.assumeTrue(BuiltinSignatures.ed25519.isSupported(), 
"Ed25519 host keys are not supported");
+        // Start manually so unsupported algorithms skip before pulling or 
starting the image.
+        try (GenericContainer<?> server = new 
GenericContainer<>(DockerImageName.parse(OQS_OPENSSH_IMAGE))
+                .withExposedPorts(22)
+                .withEnv("TEST_PASSWORD", "test")
+                // The image defaults to pure KEX only. Override it for the 
hybrid connectivity test.
+                .withCommand("-o", "KexAlgorithms=" + factory.getName() /* , 
"-o", "LogLevel=DEBUG3" */)
+                .waitingFor(Wait.forLogMessage(".*Server listening on.*port 
22.*\\n", 1))
+                .withStartupTimeout(Duration.ofMinutes(2))
+                .withLogConsumer(new Slf4jLogConsumer(LOG))) {
+            try {
+                server.start();
+            } catch (ContainerLaunchException | ContainerFetchException e) {
+                if (!isImageUnavailable(e)) {
+                    throw e;
+                }
+                Assumptions.abort("OQS-OpenSSH image not available: " + 
e.getMessage());
+            }
+            SshClient client = setupTestClient();
+            
client.setKeyExchangeFactories(Collections.singletonList(ClientBuilder.DH2KEX.apply(factory)));
+            
client.setSignatureFactories(Collections.singletonList(BuiltinSignatures.ed25519));
+            client.start();
+            try (ClientSession session = client.connect("test", 
server.getHost(), server.getMappedPort(22))
+                    .verify(CONNECT_TIMEOUT).getSession()) {
+                session.addPasswordIdentity("test");
+                session.auth().verify(AUTH_TIMEOUT);
+                assertTrue(session.isAuthenticated(), "Password authentication 
failed");
+                assertEquals(factory.getName(), 
session.getNegotiatedKexParameter(KexProposalOption.ALGORITHMS));
+                assertEquals("CONNECTED_OK", 
session.executeRemoteCommand("echo CONNECTED_OK", DEFAULT_TIMEOUT).trim());
+            } finally {
+                client.stop();
+            }
+        }
+    }
+}

Reply via email to