From fa68dc957cb20f892efa69ca6d7d0b8dc7564b04 Mon Sep 17 00:00:00 2001 From: Jeremy Norris Date: Fri, 22 Dec 2023 07:45:32 -0600 Subject: [PATCH] Add support for `sntrup761x25519-sha512@openssh.com` KEX algorithm. --- pom.xml | 3 + .../com/jcraft/jsch/DH25519SNTRUP761.java | 37 +++ src/main/java/com/jcraft/jsch/DHECN.java | 8 +- src/main/java/com/jcraft/jsch/DHGEX.java | 8 +- src/main/java/com/jcraft/jsch/DHGN.java | 7 +- src/main/java/com/jcraft/jsch/DHXEC.java | 7 +- src/main/java/com/jcraft/jsch/DHXECKEM.java | 223 ++++++++++++++++++ src/main/java/com/jcraft/jsch/JSch.java | 5 +- src/main/java/com/jcraft/jsch/KEM.java | 35 +++ .../java/com/jcraft/jsch/KeyExchange.java | 4 +- src/main/java/com/jcraft/jsch/Session.java | 15 +- .../annotations/SuppressForbiddenApi.java | 13 + .../java/com/jcraft/jsch/bc/SNTRUP761.java | 73 ++++++ .../java/com/jcraft/jsch/Algorithms4IT.java | 191 +++++++++++++++ .../docker/sshd_config.ExtInfoInAuthIT | 2 +- .../resources/docker/sshd_config.openssh96 | 2 +- 16 files changed, 615 insertions(+), 18 deletions(-) create mode 100644 src/main/java/com/jcraft/jsch/DH25519SNTRUP761.java create mode 100644 src/main/java/com/jcraft/jsch/DHXECKEM.java create mode 100644 src/main/java/com/jcraft/jsch/KEM.java create mode 100644 src/main/java/com/jcraft/jsch/annotations/SuppressForbiddenApi.java create mode 100644 src/main/java/com/jcraft/jsch/bc/SNTRUP761.java create mode 100644 src/test/java/com/jcraft/jsch/Algorithms4IT.java diff --git a/pom.xml b/pom.xml index 34d69187..b6adb15d 100644 --- a/pom.xml +++ b/pom.xml @@ -661,6 +661,9 @@ jdk-non-portable jdk-reflection + + com.jcraft.jsch.annotations.SuppressForbiddenApi + diff --git a/src/main/java/com/jcraft/jsch/DH25519SNTRUP761.java b/src/main/java/com/jcraft/jsch/DH25519SNTRUP761.java new file mode 100644 index 00000000..ceab96ba --- /dev/null +++ b/src/main/java/com/jcraft/jsch/DH25519SNTRUP761.java @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2015-2018 ymnk, JCraft,Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted + * provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions + * and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials provided with + * the distribution. + * + * 3. The names of the authors may not be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jcraft.jsch; + +class DH25519SNTRUP761 extends DHXECKEM { + public DH25519SNTRUP761() { + kem_name = "sntrup761"; + sha_name = "sha-512"; + curve_name = "X25519"; + encapsulation_len = 1039; + key_len = 32; + } +} diff --git a/src/main/java/com/jcraft/jsch/DHECN.java b/src/main/java/com/jcraft/jsch/DHECN.java index f28c9ff8..8b8095bb 100644 --- a/src/main/java/com/jcraft/jsch/DHECN.java +++ b/src/main/java/com/jcraft/jsch/DHECN.java @@ -159,7 +159,7 @@ public boolean next(Buffer _buf) throws Exception { buf.putString(K_S); buf.putString(Q_C); buf.putString(Q_S); - buf.putMPInt(K); + putK(buf); byte[] foo = new byte[buf.getLength()]; buf.getByte(foo); @@ -185,4 +185,10 @@ public boolean next(Buffer _buf) throws Exception { public int getState() { return state; } + + + @Override + void putK(Buffer b) { + b.putMPInt(K); + } } diff --git a/src/main/java/com/jcraft/jsch/DHGEX.java b/src/main/java/com/jcraft/jsch/DHGEX.java index 84aa51d4..eb66464c 100644 --- a/src/main/java/com/jcraft/jsch/DHGEX.java +++ b/src/main/java/com/jcraft/jsch/DHGEX.java @@ -208,7 +208,7 @@ public boolean next(Buffer _buf) throws Exception { buf.putMPInt(g); buf.putMPInt(e); buf.putMPInt(f); - buf.putMPInt(K); + putK(buf); byte[] foo = new byte[buf.getLength()]; buf.getByte(foo); @@ -238,6 +238,12 @@ public int getState() { return state; } + + @Override + void putK(Buffer b) { + b.putMPInt(K); + } + static boolean checkInvalidSize(int size) { return (size < 1024 || size > 8192 || size % 1024 != 0); } diff --git a/src/main/java/com/jcraft/jsch/DHGN.java b/src/main/java/com/jcraft/jsch/DHGN.java index 44aaadf8..4a66a848 100644 --- a/src/main/java/com/jcraft/jsch/DHGN.java +++ b/src/main/java/com/jcraft/jsch/DHGN.java @@ -156,7 +156,7 @@ public boolean next(Buffer _buf) throws Exception { buf.putString(K_S); buf.putMPInt(e); buf.putMPInt(f); - buf.putMPInt(K); + putK(buf); byte[] foo = new byte[buf.getLength()]; buf.getByte(foo); sha.update(foo, 0, foo.length); @@ -182,4 +182,9 @@ public boolean next(Buffer _buf) throws Exception { public int getState() { return state; } + + @Override + void putK(Buffer b) { + b.putMPInt(K); + } } diff --git a/src/main/java/com/jcraft/jsch/DHXEC.java b/src/main/java/com/jcraft/jsch/DHXEC.java index a3576189..b8c0f857 100644 --- a/src/main/java/com/jcraft/jsch/DHXEC.java +++ b/src/main/java/com/jcraft/jsch/DHXEC.java @@ -171,7 +171,7 @@ public boolean next(Buffer _buf) throws Exception { buf.putString(K_S); buf.putString(Q_C); buf.putString(Q_S); - buf.putMPInt(K); + putK(buf); byte[] foo = new byte[buf.getLength()]; buf.getByte(foo); @@ -197,4 +197,9 @@ public boolean next(Buffer _buf) throws Exception { public int getState() { return state; } + + @Override + void putK(Buffer b) { + b.putMPInt(K); + } } diff --git a/src/main/java/com/jcraft/jsch/DHXECKEM.java b/src/main/java/com/jcraft/jsch/DHXECKEM.java new file mode 100644 index 00000000..8d544dd2 --- /dev/null +++ b/src/main/java/com/jcraft/jsch/DHXECKEM.java @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2015-2018 ymnk, JCraft,Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted + * provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions + * and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials provided with + * the distribution. + * + * 3. The names of the authors may not be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jcraft.jsch; + +abstract class DHXECKEM extends KeyExchange { + + private static final int SSH_MSG_KEX_ECDH_INIT = 30; + private static final int SSH_MSG_KEX_ECDH_REPLY = 31; + private int state; + + byte[] Q_C; + + byte[] V_S; + byte[] V_C; + byte[] I_S; + byte[] I_C; + + byte[] e; + + private Buffer buf; + private Packet packet; + + private KEM kem; + private XDH xdh; + + protected String kem_name; + protected String sha_name; + protected String curve_name; + protected int encapsulation_len; + protected int key_len; + + @Override + public void init(Session session, byte[] V_S, byte[] V_C, byte[] I_S, byte[] I_C) + throws Exception { + this.V_S = V_S; + this.V_C = V_C; + this.I_S = I_S; + this.I_C = I_C; + + try { + Class c = Class.forName(session.getConfig(sha_name)).asSubclass(HASH.class); + sha = c.getDeclaredConstructor().newInstance(); + sha.init(); + } catch (Exception e) { + throw new JSchException(e.toString(), e); + } + + buf = new Buffer(); + packet = new Packet(buf); + + packet.reset(); + buf.putByte((byte) SSH_MSG_KEX_ECDH_INIT); + + try { + Class k = Class.forName(session.getConfig(kem_name)).asSubclass(KEM.class); + kem = k.getDeclaredConstructor().newInstance(); + kem.init(); + + Class c = Class.forName(session.getConfig("xdh")).asSubclass(XDH.class); + xdh = c.getDeclaredConstructor().newInstance(); + xdh.init(curve_name, key_len); + + byte[] kem_public_key_C = kem.getPublicKey(); + byte[] xec_public_key_C = xdh.getQ(); + Q_C = new byte[kem_public_key_C.length + xec_public_key_C.length]; + System.arraycopy(kem_public_key_C, 0, Q_C, 0, kem_public_key_C.length); + System.arraycopy(xec_public_key_C, 0, Q_C, kem_public_key_C.length, xec_public_key_C.length); + buf.putString(Q_C); + } catch (Exception | NoClassDefFoundError e) { + throw new JSchException(e.toString(), e); + } + + if (V_S == null) { // This is a really ugly hack for Session.checkKexes ;-( + return; + } + + session.write(packet); + + if (session.getLogger().isEnabled(Logger.INFO)) { + session.getLogger().log(Logger.INFO, "SSH_MSG_KEX_ECDH_INIT sent"); + session.getLogger().log(Logger.INFO, "expecting SSH_MSG_KEX_ECDH_REPLY"); + } + + state = SSH_MSG_KEX_ECDH_REPLY; + } + + @Override + public boolean next(Buffer _buf) throws Exception { + int i, j; + switch (state) { + case SSH_MSG_KEX_ECDH_REPLY: + // The server responds with: + // byte SSH_MSG_KEX_ECDH_REPLY + // string K_S, server's public host key + // string Q_S, server's ephemeral public key octet string + // string the signature on the exchange hash + j = _buf.getInt(); + j = _buf.getByte(); + j = _buf.getByte(); + if (j != SSH_MSG_KEX_ECDH_REPLY) { + if (session.getLogger().isEnabled(Logger.ERROR)) { + session.getLogger().log(Logger.ERROR, "type: must be SSH_MSG_KEX_ECDH_REPLY " + j); + } + return false; + } + + K_S = _buf.getString(); + + byte[] Q_S = _buf.getString(); + if (Q_S.length != encapsulation_len + key_len) { + return false; + } + + byte[] encapsulation = new byte[encapsulation_len]; + byte[] xec_public_key_S = new byte[key_len]; + System.arraycopy(Q_S, 0, encapsulation, 0, encapsulation_len); + System.arraycopy(Q_S, encapsulation_len, xec_public_key_S, 0, key_len); + + // RFC 5656, + // 4. ECDH Key Exchange + // All elliptic curve public keys MUST be validated after they are + // received. An example of a validation algorithm can be found in + // Section 3.2.2 of [SEC1]. If a key fails validation, + // the key exchange MUST fail. + if (!xdh.validate(xec_public_key_S)) { + return false; + } + + byte[] tmp = kem.decapsulate(encapsulation); + sha.update(tmp, 0, tmp.length); + tmp = xdh.getSecret(xec_public_key_S); + tmp = normalize(tmp); + sha.update(tmp, 0, tmp.length); + K = sha.digest(); + + byte[] sig_of_H = _buf.getString(); + + // The hash H is computed as the HASH hash of the concatenation of the + // following: + // string V_C, client's identification string (CR and LF excluded) + // string V_S, server's identification string (CR and LF excluded) + // string I_C, payload of the client's SSH_MSG_KEXINIT + // string I_S, payload of the server's SSH_MSG_KEXINIT + // string K_S, server's public host key + // string Q_C, client's ephemeral public key octet string + // string Q_S, server's ephemeral public key octet string + // string K, shared secret + + // draft-josefsson-ntruprime-ssh-02, + // 3. Key Exchange Method: sntrup761x25519-sha512 + // ... + // The SSH_MSG_KEX_ECDH_REPLY's signature value is computed as described + // in [RFC5656] with the following changes. Instead of encoding the + // shared secret K as 'mpint', it MUST be encoded as 'string'. The + // shared secret K value MUST be the 64-byte output octet string of the + // SHA-512 hash computed with the input as the 32-byte octet string key + // output from the key encapsulation mechanism of sntrup761 concatenated + // with the 32-byte octet string of X25519(a, X25519(b, 9)) = X25519(b, + // X25519(a, 9)). + buf.reset(); + buf.putString(V_C); + buf.putString(V_S); + buf.putString(I_C); + buf.putString(I_S); + buf.putString(K_S); + buf.putString(Q_C); + buf.putString(Q_S); + putK(buf); + byte[] foo = new byte[buf.getLength()]; + buf.getByte(foo); + + sha.update(foo, 0, foo.length); + H = sha.digest(); + + i = 0; + j = 0; + j = ((K_S[i++] << 24) & 0xff000000) | ((K_S[i++] << 16) & 0x00ff0000) + | ((K_S[i++] << 8) & 0x0000ff00) | ((K_S[i++]) & 0x000000ff); + String alg = Util.byte2str(K_S, i, j); + i += j; + + boolean result = verify(alg, K_S, i, sig_of_H); + + state = STATE_END; + return result; + } + return false; + } + + @Override + public int getState() { + return state; + } + + @Override + void putK(Buffer b) { + b.putString(K); + } +} diff --git a/src/main/java/com/jcraft/jsch/JSch.java b/src/main/java/com/jcraft/jsch/JSch.java index 0c86f25c..a089dd66 100644 --- a/src/main/java/com/jcraft/jsch/JSch.java +++ b/src/main/java/com/jcraft/jsch/JSch.java @@ -103,6 +103,9 @@ public class JSch { config.put("curve25519-sha256", "com.jcraft.jsch.DH25519"); config.put("curve25519-sha256@libssh.org", "com.jcraft.jsch.DH25519"); config.put("curve448-sha512", "com.jcraft.jsch.DH448"); + config.put("sntrup761x25519-sha512@openssh.com", "com.jcraft.jsch.DH25519SNTRUP761"); + + config.put("sntrup761", "com.jcraft.jsch.bc.SNTRUP761"); config.put("dh", "com.jcraft.jsch.jce.DH"); config.put("3des-cbc", "com.jcraft.jsch.jce.TripleDESCBC"); @@ -239,7 +242,7 @@ public class JSch { Util.getSystemProperty("jsch.check_ciphers", "chacha20-poly1305@openssh.com")); config.put("CheckMacs", Util.getSystemProperty("jsch.check_macs", "")); config.put("CheckKexes", Util.getSystemProperty("jsch.check_kexes", - "curve25519-sha256,curve25519-sha256@libssh.org,curve448-sha512")); + "sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org,curve448-sha512")); config.put("CheckSignatures", Util.getSystemProperty("jsch.check_signatures", "ssh-ed25519,ssh-ed448")); config.put("FingerprintHash", Util.getSystemProperty("jsch.fingerprint_hash", "sha256")); diff --git a/src/main/java/com/jcraft/jsch/KEM.java b/src/main/java/com/jcraft/jsch/KEM.java new file mode 100644 index 00000000..90dcaacf --- /dev/null +++ b/src/main/java/com/jcraft/jsch/KEM.java @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2015-2018 ymnk, JCraft,Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted + * provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions + * and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials provided with + * the distribution. + * + * 3. The names of the authors may not be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jcraft.jsch; + +public interface KEM { + void init() throws Exception; + + byte[] getPublicKey() throws Exception; + + byte[] decapsulate(byte[] encapsulation) throws Exception; +} diff --git a/src/main/java/com/jcraft/jsch/KeyExchange.java b/src/main/java/com/jcraft/jsch/KeyExchange.java index e686be76..b6290769 100644 --- a/src/main/java/com/jcraft/jsch/KeyExchange.java +++ b/src/main/java/com/jcraft/jsch/KeyExchange.java @@ -211,9 +211,7 @@ public String getFingerPrint() { return Util.getFingerPrint(hash, getHostKey(), true, false); } - byte[] getK() { - return K; - } + abstract void putK(Buffer b); byte[] getH() { return H; diff --git a/src/main/java/com/jcraft/jsch/Session.java b/src/main/java/com/jcraft/jsch/Session.java index 57302763..609dfed6 100644 --- a/src/main/java/com/jcraft/jsch/Session.java +++ b/src/main/java/com/jcraft/jsch/Session.java @@ -1473,7 +1473,6 @@ private void receive_newkeys(Buffer buf, KeyExchange kex) throws Exception { } private void updateKeys(KeyExchange kex) throws Exception { - byte[] K = kex.getK(); byte[] H = kex.getH(); HASH hash = kex.getHash(); @@ -1491,7 +1490,7 @@ private void updateKeys(KeyExchange kex) throws Exception { */ buf.reset(); - buf.putMPInt(K); + kex.putK(buf); buf.putByte(H); buf.putByte((byte) 0x41); buf.putByte(session_id); @@ -1530,7 +1529,7 @@ private void updateKeys(KeyExchange kex) throws Exception { s2ccipher = cc.getDeclaredConstructor().newInstance(); while (s2ccipher.getBlockSize() > Es2c.length) { buf.reset(); - buf.putMPInt(K); + kex.putK(buf); buf.putByte(H); buf.putByte(Es2c); hash.update(buf.buffer, 0, buf.index); @@ -1547,7 +1546,7 @@ private void updateKeys(KeyExchange kex) throws Exception { method = guess[KeyExchange.PROPOSAL_MAC_ALGS_STOC]; cm = Class.forName(getConfig(method)).asSubclass(MAC.class); s2cmac = cm.getDeclaredConstructor().newInstance(); - MACs2c = expandKey(buf, K, H, MACs2c, hash, s2cmac.getBlockSize()); + MACs2c = expandKey(buf, kex, H, MACs2c, hash, s2cmac.getBlockSize()); s2cmac.init(MACs2c); // mac_buf=new byte[s2cmac.getBlockSize()]; s2cmac_result1 = new byte[s2cmac.getBlockSize()]; @@ -1559,7 +1558,7 @@ private void updateKeys(KeyExchange kex) throws Exception { c2scipher = cc.getDeclaredConstructor().newInstance(); while (c2scipher.getBlockSize() > Ec2s.length) { buf.reset(); - buf.putMPInt(K); + kex.putK(buf); buf.putByte(H); buf.putByte(Ec2s); hash.update(buf.buffer, 0, buf.index); @@ -1576,7 +1575,7 @@ private void updateKeys(KeyExchange kex) throws Exception { method = guess[KeyExchange.PROPOSAL_MAC_ALGS_CTOS]; cm = Class.forName(getConfig(method)).asSubclass(MAC.class); c2smac = cm.getDeclaredConstructor().newInstance(); - MACc2s = expandKey(buf, K, H, MACc2s, hash, c2smac.getBlockSize()); + MACc2s = expandKey(buf, kex, H, MACc2s, hash, c2smac.getBlockSize()); c2smac.init(MACc2s); } @@ -1602,13 +1601,13 @@ private void updateKeys(KeyExchange kex) throws Exception { * of this value. In other words: K1 = HASH(K || H || X || session_id) (X is e.g., "A") K2 = * HASH(K || H || K1) K3 = HASH(K || H || K1 || K2) ... key = K1 || K2 || K3 || ... */ - private byte[] expandKey(Buffer buf, byte[] K, byte[] H, byte[] key, HASH hash, + private byte[] expandKey(Buffer buf, KeyExchange kex, byte[] H, byte[] key, HASH hash, int required_length) throws Exception { byte[] result = key; int size = hash.getBlockSize(); while (result.length < required_length) { buf.reset(); - buf.putMPInt(K); + kex.putK(buf); buf.putByte(H); buf.putByte(result); hash.update(buf.buffer, 0, buf.index); diff --git a/src/main/java/com/jcraft/jsch/annotations/SuppressForbiddenApi.java b/src/main/java/com/jcraft/jsch/annotations/SuppressForbiddenApi.java new file mode 100644 index 00000000..b3494689 --- /dev/null +++ b/src/main/java/com/jcraft/jsch/annotations/SuppressForbiddenApi.java @@ -0,0 +1,13 @@ +package com.jcraft.jsch.annotations; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; +import java.lang.annotation.ElementType; + +@Retention(RetentionPolicy.CLASS) +@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.LOCAL_VARIABLE, ElementType.METHOD, + ElementType.PARAMETER, ElementType.TYPE}) +public @interface SuppressForbiddenApi { + String[] value(); +} diff --git a/src/main/java/com/jcraft/jsch/bc/SNTRUP761.java b/src/main/java/com/jcraft/jsch/bc/SNTRUP761.java new file mode 100644 index 00000000..af7628a8 --- /dev/null +++ b/src/main/java/com/jcraft/jsch/bc/SNTRUP761.java @@ -0,0 +1,73 @@ +/* + * Copyright (c) 2015-2018 ymnk, JCraft,Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are permitted + * provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of conditions + * and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials provided with + * the distribution. + * + * 3. The names of the authors may not be used to endorse or promote products derived from this + * software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL JCRAFT, INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR + * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.jcraft.jsch.bc; + +import com.jcraft.jsch.KEM; +import com.jcraft.jsch.annotations.SuppressForbiddenApi; +import java.lang.reflect.Constructor; +import java.security.SecureRandom; +import org.bouncycastle.crypto.AsymmetricCipherKeyPair; +import org.bouncycastle.pqc.crypto.ntruprime.*; + +public class SNTRUP761 implements KEM { + SNTRUPrimeKEMExtractor extractor; + SNTRUPrimePublicKeyParameters publicKey; + + @Override + public void init() throws Exception { + SNTRUPrimeParameters sntrup761 = SNTRUPrimeParameters.sntrup761.getSessionKeySize() / 8 == 32 + ? SNTRUPrimeParameters.sntrup761 + : sntrup761(); + SNTRUPrimeKeyPairGenerator kpg = new SNTRUPrimeKeyPairGenerator(); + kpg.init(new SNTRUPrimeKeyGenerationParameters(new SecureRandom(), sntrup761)); + AsymmetricCipherKeyPair kp = kpg.generateKeyPair(); + extractor = new SNTRUPrimeKEMExtractor((SNTRUPrimePrivateKeyParameters) kp.getPrivate()); + publicKey = (SNTRUPrimePublicKeyParameters) kp.getPublic(); + } + + @Override + public byte[] getPublicKey() throws Exception { + return publicKey.getEncoded(); + } + + @Override + public byte[] decapsulate(byte[] encapsulation) throws Exception { + return extractor.extractSecret(encapsulation); + } + + // Bouncy Castle before 1.78 defines sharedKeyBytes differently than OpenSSH (16 instead of 32) + // https://github.com/bcgit/bc-java/issues/1554 + // https://github.com/bcgit/bc-java/commit/db3ae60 + @SuppressForbiddenApi("jdk-reflection") + static SNTRUPrimeParameters sntrup761() throws Exception { + Constructor c = + SNTRUPrimeParameters.class.getDeclaredConstructor(String.class, int.class, int.class, + int.class, int.class, int.class, int.class, int.class, int.class); + c.setAccessible(true); + return c.newInstance("sntrup761", 761, 4591, 286, 1158, 1007, 1158, 1763, 32); + } +} diff --git a/src/test/java/com/jcraft/jsch/Algorithms4IT.java b/src/test/java/com/jcraft/jsch/Algorithms4IT.java new file mode 100644 index 00000000..0d5632f9 --- /dev/null +++ b/src/test/java/com/jcraft/jsch/Algorithms4IT.java @@ -0,0 +1,191 @@ +package com.jcraft.jsch; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static java.util.stream.Collectors.toList; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import com.github.valfirst.slf4jtest.LoggingEvent; +import com.github.valfirst.slf4jtest.TestLogger; +import com.github.valfirst.slf4jtest.TestLoggerFactory; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Base64; +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.Random; +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.io.TempDir; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; +import org.testcontainers.containers.GenericContainer; +import org.testcontainers.containers.output.Slf4jLogConsumer; +import org.testcontainers.images.builder.ImageFromDockerfile; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; + +@Testcontainers +public class Algorithms4IT { + + private static final int timeout = 2000; + private static final DigestUtils sha256sum = new DigestUtils(DigestUtils.getSha256Digest()); + private static final TestLogger jschLogger = TestLoggerFactory.getTestLogger(JSch.class); + private static final TestLogger sshdLogger = TestLoggerFactory.getTestLogger(Algorithms4IT.class); + + @TempDir + public Path tmpDir; + private Path in; + private Path out; + private String hash; + private Slf4jLogConsumer sshdLogConsumer; + + @Container + public GenericContainer sshd = new GenericContainer<>( + new ImageFromDockerfile().withFileFromClasspath("ssh_host_rsa_key", "docker/ssh_host_rsa_key") + .withFileFromClasspath("ssh_host_rsa_key.pub", "docker/ssh_host_rsa_key.pub") + .withFileFromClasspath("ssh_host_ecdsa256_key", "docker/ssh_host_ecdsa256_key") + .withFileFromClasspath("ssh_host_ecdsa256_key.pub", "docker/ssh_host_ecdsa256_key.pub") + .withFileFromClasspath("ssh_host_ecdsa384_key", "docker/ssh_host_ecdsa384_key") + .withFileFromClasspath("ssh_host_ecdsa384_key.pub", "docker/ssh_host_ecdsa384_key.pub") + .withFileFromClasspath("ssh_host_ecdsa521_key", "docker/ssh_host_ecdsa521_key") + .withFileFromClasspath("ssh_host_ecdsa521_key.pub", "docker/ssh_host_ecdsa521_key.pub") + .withFileFromClasspath("ssh_host_ed25519_key", "docker/ssh_host_ed25519_key") + .withFileFromClasspath("ssh_host_ed25519_key.pub", "docker/ssh_host_ed25519_key.pub") + .withFileFromClasspath("ssh_host_dsa_key", "docker/ssh_host_dsa_key") + .withFileFromClasspath("ssh_host_dsa_key.pub", "docker/ssh_host_dsa_key.pub") + .withFileFromClasspath("sshd_config", "docker/sshd_config.openssh96") + .withFileFromClasspath("authorized_keys", "docker/authorized_keys") + .withFileFromClasspath("Dockerfile", "docker/Dockerfile.openssh96")) + .withExposedPorts(22); + + @BeforeAll + public static void beforeAll() { + JSch.setLogger(new Slf4jLogger()); + } + + @BeforeEach + public void beforeEach() throws IOException { + if (sshdLogConsumer == null) { + sshdLogConsumer = new Slf4jLogConsumer(sshdLogger); + sshd.followOutput(sshdLogConsumer); + } + + in = tmpDir.resolve("in"); + out = tmpDir.resolve("out"); + Files.createFile(in); + try (OutputStream os = Files.newOutputStream(in)) { + byte[] data = new byte[1024]; + for (int i = 0; i < 1024 * 100; i += 1024) { + new Random().nextBytes(data); + os.write(data); + } + } + hash = sha256sum.digestAsHex(in); + + jschLogger.clearAll(); + sshdLogger.clearAll(); + } + + @AfterAll + public static void afterAll() { + JSch.setLogger(null); + jschLogger.clearAll(); + sshdLogger.clearAll(); + } + + @ParameterizedTest + @ValueSource(strings = {"sntrup761x25519-sha512@openssh.com"}) + public void testBCKEXs(String kex) throws Exception { + JSch ssh = createRSAIdentity(); + Session session = createSession(ssh); + session.setConfig("kex", kex); + doSftp(session, true); + + String expected = String.format(Locale.ROOT, "kex: algorithm: %s.*", kex); + checkLogs(expected); + } + + private JSch createRSAIdentity() throws Exception { + HostKey hostKey = readHostKey(getResourceFile("docker/ssh_host_rsa_key.pub")); + JSch ssh = new JSch(); + ssh.addIdentity(getResourceFile("docker/id_rsa"), getResourceFile("docker/id_rsa.pub"), null); + ssh.getHostKeyRepository().add(hostKey, null); + return ssh; + } + + private HostKey readHostKey(String fileName) throws Exception { + List lines = Files.readAllLines(Paths.get(fileName), UTF_8); + String[] split = lines.get(0).split("\\s+"); + String hostname = + String.format(Locale.ROOT, "[%s]:%d", sshd.getHost(), sshd.getFirstMappedPort()); + return new HostKey(hostname, Base64.getDecoder().decode(split[1])); + } + + private Session createSession(JSch ssh) throws Exception { + Session session = ssh.getSession("root", sshd.getHost(), sshd.getFirstMappedPort()); + session.setConfig("StrictHostKeyChecking", "yes"); + session.setConfig("PreferredAuthentications", "publickey"); + return session; + } + + private void doSftp(Session session, boolean debugException) throws Exception { + try { + session.setTimeout(timeout); + session.connect(); + ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp"); + sftp.connect(timeout); + sftp.put(in.toString(), "/root/test"); + sftp.get("/root/test", out.toString()); + sftp.disconnect(); + session.disconnect(); + } catch (Exception e) { + if (debugException) { + printInfo(); + } + throw e; + } + + assertEquals(1024L * 100L, Files.size(out)); + assertEquals(hash, sha256sum.digestAsHex(out)); + } + + private void printInfo() { + jschLogger.getAllLoggingEvents().stream().map(LoggingEvent::getFormattedMessage) + .forEach(System.out::println); + sshdLogger.getAllLoggingEvents().stream().map(LoggingEvent::getFormattedMessage) + .forEach(System.out::println); + System.out.println(""); + System.out.println(""); + System.out.println(""); + } + + private void checkLogs(String expected) { + Optional actualJsch = jschLogger.getAllLoggingEvents().stream() + .map(LoggingEvent::getFormattedMessage).filter(msg -> msg.matches(expected)).findFirst(); + // Skip OpenSSH log checks, as log output from Docker falls behind and these assertions + // frequently run before they are output + // Optional actualSshd = + // sshdLogger.getAllLoggingEvents().stream() + // .map(LoggingEvent::getFormattedMessage) + // .filter(msg -> msg.matches("STDERR: debug1: " + expected)) + // .findFirst(); + try { + assertTrue(actualJsch.isPresent(), () -> "JSch: " + expected); + // assertTrue(actualSshd.isPresent(), () -> "sshd: " + expected); + } catch (AssertionError e) { + printInfo(); + throw e; + } + } + + private String getResourceFile(String fileName) { + return ResourceUtil.getResourceFile(getClass(), fileName); + } +} diff --git a/src/test/resources/docker/sshd_config.ExtInfoInAuthIT b/src/test/resources/docker/sshd_config.ExtInfoInAuthIT index d63c7f83..73dd194a 100644 --- a/src/test/resources/docker/sshd_config.ExtInfoInAuthIT +++ b/src/test/resources/docker/sshd_config.ExtInfoInAuthIT @@ -14,7 +14,7 @@ HostKey /etc/ssh/ssh_host_ecdsa521_key HostKey /etc/ssh/ssh_host_ed25519_key HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_dsa_key -KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group18-sha512,diffie-hellman-group16-sha512,diffie-hellman-group14-sha256,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 +KexAlgorithms sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group18-sha512,diffie-hellman-group16-sha512,diffie-hellman-group14-sha256,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 HostKeyAlgorithms ecdsa-sha2-nistp521,ecdsa-sha2-nistp384,ecdsa-sha2-nistp256,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha1-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,hmac-sha1,hmac-sha1-96-etm@openssh.com,hmac-sha1-96,hmac-md5-etm@openssh.com,hmac-md5,hmac-md5-96-etm@openssh.com,hmac-md5-96 diff --git a/src/test/resources/docker/sshd_config.openssh96 b/src/test/resources/docker/sshd_config.openssh96 index 8d7bcba1..12c4064f 100644 --- a/src/test/resources/docker/sshd_config.openssh96 +++ b/src/test/resources/docker/sshd_config.openssh96 @@ -14,7 +14,7 @@ HostKey /etc/ssh/ssh_host_ecdsa521_key HostKey /etc/ssh/ssh_host_ed25519_key HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_dsa_key -KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group18-sha512,diffie-hellman-group16-sha512,diffie-hellman-group14-sha256,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 +KexAlgorithms sntrup761x25519-sha512@openssh.com,curve25519-sha256,curve25519-sha256@libssh.org,ecdh-sha2-nistp521,ecdh-sha2-nistp384,ecdh-sha2-nistp256,diffie-hellman-group18-sha512,diffie-hellman-group16-sha512,diffie-hellman-group14-sha256,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1 HostKeyAlgorithms ecdsa-sha2-nistp521,ecdsa-sha2-nistp384,ecdsa-sha2-nistp256,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa,ssh-dss Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr,aes256-cbc,aes192-cbc,aes128-cbc MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha1-etm@openssh.com,hmac-sha2-512,hmac-sha2-256,hmac-sha1,hmac-sha1-96-etm@openssh.com,hmac-sha1-96,hmac-md5-etm@openssh.com,hmac-md5,hmac-md5-96-etm@openssh.com,hmac-md5-96