From 1538ad0387158e7ae319f06059bee9761d2ab921 Mon Sep 17 00:00:00 2001 From: Arno Zeller Date: Thu, 12 Nov 2026 08:20:43 +0000 Subject: [PATCH 01/10] 8371769: TestMemoryInvisibleParent.java fails with java.nio.file.AccessDeniedException Backport-of: 3fd551f9926601b05a13a22b556d55425a37ee4d --- .../docker/TestMemoryInvisibleParent.java | 24 +++++++++++-------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/test/hotspot/jtreg/containers/docker/TestMemoryInvisibleParent.java b/test/hotspot/jtreg/containers/docker/TestMemoryInvisibleParent.java index 29856590469a..4854f6631019 100644 --- a/test/hotspot/jtreg/containers/docker/TestMemoryInvisibleParent.java +++ b/test/hotspot/jtreg/containers/docker/TestMemoryInvisibleParent.java @@ -33,6 +33,7 @@ import java.nio.file.Files; import java.util.ArrayList; +import jdk.test.lib.Platform; import jtreg.SkippedException; /* @@ -61,6 +62,9 @@ public static void main(String[] args) throws Exception { if (DockerTestUtils.isRootless()) { throw new SkippedException("Test skipped in rootless mode"); } + if (!Platform.isRoot()) { + throw new SkippedException("Test should be run as root"); + } DockerTestUtils.buildJdkContainerImage(imageName); if ("cgroupv1".equals(metrics.getProvider())) { @@ -81,16 +85,16 @@ private static void testMemoryLimitHiddenParent(String valueToSet, String expect Common.logNewTestCase("Cgroup V1 hidden parent memory limit: " + valueToSet); try { - String cgroupParent = setParentWithLimit(valueToSet); - DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java", "-version", "-Xlog:os+container=trace"); - opts.appendTestJavaOptions = false; - if (DockerTestUtils.isPodman()) { - // Podman needs to run this test with engine option --cgroup-manager=cgroupfs - opts.addEngineOpts("--cgroup-manager", "cgroupfs"); - } - opts.addDockerOpts("--cgroup-parent=/" + cgroupParent); - Common.run(opts) - .shouldContain("Hierarchical Memory Limit is: " + expectedValue); + String cgroupParent = setParentWithLimit(valueToSet); + DockerRunOptions opts = new DockerRunOptions(imageName, "/jdk/bin/java", "-version", "-Xlog:os+container=trace"); + opts.appendTestJavaOptions = false; + if (DockerTestUtils.isPodman()) { + // Podman needs to run this test with engine option --cgroup-manager=cgroupfs + opts.addEngineOpts("--cgroup-manager", "cgroupfs"); + } + opts.addDockerOpts("--cgroup-parent=/" + cgroupParent); + Common.run(opts) + .shouldContain("Hierarchical Memory Limit is: " + expectedValue); } finally { // Reset the parent memory limit to unlimited (-1) setParentWithLimit(UNLIMITED); From 7ba258172911013c100c550ebfce6cc30c3278d0 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Thu, 12 Nov 2026 11:25:31 +0000 Subject: [PATCH 02/10] 8373474: 2 Unintentional format string defect groups in jabswitch.cpp Backport-of: 72e1e15779c3d7846f267c0dfd98191b99a55548 --- .../windows/native/jabswitch/jabswitch.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/src/jdk.accessibility/windows/native/jabswitch/jabswitch.cpp b/src/jdk.accessibility/windows/native/jabswitch/jabswitch.cpp index 62546b4dd78e..fdd7ff524da0 100644 --- a/src/jdk.accessibility/windows/native/jabswitch/jabswitch.cpp +++ b/src/jdk.accessibility/windows/native/jabswitch/jabswitch.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -226,9 +226,9 @@ int modify(bool enable) { printf("Couldn't create file: %s\n", path); perror("Error"); } else { - char str[100] = "assistive_technologies=com.sun.java.accessibility.AccessBridge\n"; - strcat_s(str, "screen_magnifier_present=true\n"); - fprintf(origFile, str); + fprintf(origFile, "%s", + "assistive_technologies=com.sun.java.accessibility.AccessBridge\n" + "screen_magnifier_present=true\n"); fclose(origFile); } } else { @@ -314,11 +314,11 @@ void printVersion() { pVSInfo->dwProductVersionMS & 0xFFFF, pVSInfo->dwProductVersionLS >> 16, pVSInfo->dwProductVersionLS & 0xFFFF ); - char outputString[100]; - strcpy_s(outputString, "jabswitch "); - strcat_s(outputString, versionString); - strcat_s(outputString, "\njabswitch enables or disables the Java Access Bridge.\n"); - printf(outputString); + printf( + "jabswitch %s\n" + "jabswitch enables or disables the Java Access Bridge.\n", + versionString + ); } int regEnable() { From 198fb990321e2ab8be9c4f3715812f805cf44556 Mon Sep 17 00:00:00 2001 From: Roland Mesde Date: Fri, 13 Nov 2026 18:01:29 +0000 Subject: [PATCH 03/10] 8314323: Implement JEP 527: TLS 1.3 Hybrid Key Exchange Reviewed-by: simonis, sgehwolf, andrew Backport-of: 83e90e7d76e9ca804384d47a4d529e91f79d8981 --- .../classes/sun/security/ssl/DHasKEM.java | 254 ++++++++++ .../classes/sun/security/ssl/Hybrid.java | 474 ++++++++++++++++++ .../sun/security/ssl/HybridProvider.java | 141 ++++++ .../sun/security/ssl/KAKeyDerivation.java | 140 +++++- .../sun/security/ssl/KEMKeyExchange.java | 223 ++++++++ .../sun/security/ssl/KeyShareExtension.java | 113 +++-- .../classes/sun/security/ssl/NamedGroup.java | 131 ++++- .../sun/security/ssl/SSLKeyExchange.java | 6 +- .../classes/sun/security/ssl/ServerHello.java | 51 +- .../classes/sun/security/x509/X509Key.java | 6 + .../net/ssl/SSLParameters/NamedGroups.java | 57 ++- .../javax/net/ssl/TLSCommon/NamedGroup.java | 8 +- .../net/ssl/TLSv13/ClientHelloKeyShares.java | 15 +- .../javax/net/ssl/TLSv13/HRRKeyShares.java | 25 +- .../ssl/CipherSuite/DisabledCurve.java | 49 +- .../NamedGroupsWithCipherSuite.java | 76 ++- .../ssl/CipherSuite/RestrictNamedGroup.java | 7 +- .../ssl/CipherSuite/SupportedGroups.java | 32 +- .../bench/java/security/SSLHandshake.java | 25 +- .../bench/javax/crypto/full/KEMBench.java | 110 +++- .../crypto/full/KeyPairGeneratorBench.java | 34 +- 21 files changed, 1860 insertions(+), 117 deletions(-) create mode 100644 src/java.base/share/classes/sun/security/ssl/DHasKEM.java create mode 100644 src/java.base/share/classes/sun/security/ssl/Hybrid.java create mode 100644 src/java.base/share/classes/sun/security/ssl/HybridProvider.java create mode 100644 src/java.base/share/classes/sun/security/ssl/KEMKeyExchange.java diff --git a/src/java.base/share/classes/sun/security/ssl/DHasKEM.java b/src/java.base/share/classes/sun/security/ssl/DHasKEM.java new file mode 100644 index 000000000000..763013f280c2 --- /dev/null +++ b/src/java.base/share/classes/sun/security/ssl/DHasKEM.java @@ -0,0 +1,254 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.security.ssl; + +import sun.security.util.ArrayUtil; +import sun.security.util.CurveDB; +import sun.security.util.ECUtil; +import sun.security.util.NamedCurve; + +import javax.crypto.DecapsulateException; +import javax.crypto.KEM; +import javax.crypto.KEMSpi; +import javax.crypto.KeyAgreement; +import javax.crypto.SecretKey; +import java.io.IOException; +import java.math.BigInteger; +import java.security.*; +import java.security.interfaces.ECKey; +import java.security.interfaces.ECPublicKey; +import java.security.interfaces.XECKey; +import java.security.interfaces.XECPublicKey; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.ECPoint; +import java.security.spec.ECPublicKeySpec; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.security.spec.NamedParameterSpec; +import java.security.spec.XECPublicKeySpec; +import java.util.Arrays; + +/** + * The DHasKEM class presents a KEM abstraction layer over traditional + * DH-based key exchange, which can be used for either straight + * ECDH/XDH or TLS hybrid key exchanges. + * + * This class can be alongside standard full post-quantum KEMs + * when hybrid implementations are required. + */ +public class DHasKEM implements KEMSpi { + + @Override + public EncapsulatorSpi engineNewEncapsulator( + PublicKey publicKey, AlgorithmParameterSpec spec, + SecureRandom secureRandom) throws InvalidKeyException { + return new Handler(publicKey, null, secureRandom); + } + + @Override + public DecapsulatorSpi engineNewDecapsulator(PrivateKey privateKey, + AlgorithmParameterSpec spec) throws InvalidKeyException { + return new Handler(null, privateKey, null); + } + + private static final class Handler + implements KEMSpi.EncapsulatorSpi, KEMSpi.DecapsulatorSpi { + private final PublicKey pkR; + private final PrivateKey skR; + private final SecureRandom sr; + private final Params params; + + Handler(PublicKey pk, PrivateKey sk, SecureRandom sr) + throws InvalidKeyException { + this.pkR = pk; + this.skR = sk; + this.sr = sr; + this.params = paramsFromKey(pk == null ? sk : pk); + } + + @Override + public KEM.Encapsulated engineEncapsulate(int from, int to, + String algorithm) { + KeyPair kpE = params.generateKeyPair(sr); + PrivateKey skE = kpE.getPrivate(); + PublicKey pkE = kpE.getPublic(); + byte[] pkEm = params.SerializePublicKey(pkE); + try { + SecretKey dh = params.DH(algorithm, skE, pkR); + return new KEM.Encapsulated( + sub(dh, from, to), + pkEm, null); + } catch (Exception e) { + throw new ProviderException("internal error", e); + } + } + + @Override + public int engineSecretSize() { + return params.secretLen; + } + + @Override + public int engineEncapsulationSize() { + return params.publicKeyLen; + } + + @Override + public SecretKey engineDecapsulate(byte[] encapsulation, int from, + int to, String algorithm) throws DecapsulateException { + if (encapsulation.length != params.publicKeyLen) { + throw new DecapsulateException("incorrect encapsulation size"); + } + try { + PublicKey pkE = params.DeserializePublicKey(encapsulation); + SecretKey dh = params.DH(algorithm, skR, pkE); + return sub(dh, from, to); + } catch (IOException | InvalidKeyException e) { + throw new DecapsulateException("Cannot decapsulate", e); + } catch (Exception e) { + throw new ProviderException("internal error", e); + } + } + + private SecretKey sub(SecretKey key, int from, int to) { + if (from == 0 && to == params.secretLen) { + return key; + } + + // Key slicing should never happen. Otherwise, there might be + // a programming error. + throw new AssertionError( + "Unexpected key slicing: from=" + from + ", to=" + to); + } + + // This KEM is designed to be able to represent every ECDH and XDH + private Params paramsFromKey(Key k) throws InvalidKeyException { + if (k instanceof ECKey eckey) { + if (ECUtil.equals(eckey.getParams(), CurveDB.P_256)) { + return Params.P256; + } else if (ECUtil.equals(eckey.getParams(), CurveDB.P_384)) { + return Params.P384; + } else if (ECUtil.equals(eckey.getParams(), CurveDB.P_521)) { + return Params.P521; + } + } else if (k instanceof XECKey xkey + && xkey.getParams() instanceof NamedParameterSpec ns) { + if (ns.getName().equalsIgnoreCase( + NamedParameterSpec.X25519.getName())) { + return Params.X25519; + } else if (ns.getName().equalsIgnoreCase( + NamedParameterSpec.X448.getName())) { + return Params.X448; + } + } + throw new InvalidKeyException("Unsupported key"); + } + } + + private enum Params { + + P256(32, 2 * 32 + 1, + "ECDH", "EC", CurveDB.P_256), + + P384(48, 2 * 48 + 1, + "ECDH", "EC", CurveDB.P_384), + + P521(66, 2 * 66 + 1, + "ECDH", "EC", CurveDB.P_521), + + X25519(32, 32, + "XDH", "XDH", NamedParameterSpec.X25519), + + X448(56, 56, + "XDH", "XDH", NamedParameterSpec.X448); + + private final int secretLen; + private final int publicKeyLen; + private final String kaAlgorithm; + private final String keyAlgorithm; + private final AlgorithmParameterSpec spec; + + Params(int secretLen, int publicKeyLen, String kaAlgorithm, + String keyAlgorithm, AlgorithmParameterSpec spec) { + this.spec = spec; + this.secretLen = secretLen; + this.publicKeyLen = publicKeyLen; + this.kaAlgorithm = kaAlgorithm; + this.keyAlgorithm = keyAlgorithm; + } + + private boolean isEC() { + return this == P256 || this == P384 || this == P521; + } + + private KeyPair generateKeyPair(SecureRandom sr) { + try { + KeyPairGenerator g = KeyPairGenerator.getInstance(keyAlgorithm); + g.initialize(spec, sr); + return g.generateKeyPair(); + } catch (Exception e) { + throw new ProviderException("internal error", e); + } + } + + private byte[] SerializePublicKey(PublicKey k) { + if (isEC()) { + ECPoint w = ((ECPublicKey) k).getW(); + return ECUtil.encodePoint(w, ((NamedCurve) spec).getCurve()); + } else { + byte[] uArray = ((XECPublicKey) k).getU().toByteArray(); + ArrayUtil.reverse(uArray); + return Arrays.copyOf(uArray, publicKeyLen); + } + } + + private PublicKey DeserializePublicKey(byte[] data) throws + IOException, NoSuchAlgorithmException, + InvalidKeySpecException { + KeySpec keySpec; + if (isEC()) { + NamedCurve curve = (NamedCurve) this.spec; + keySpec = new ECPublicKeySpec( + ECUtil.decodePoint(data, curve.getCurve()), curve); + } else { + data = data.clone(); + ArrayUtil.reverse(data); + keySpec = new XECPublicKeySpec( + this.spec, new BigInteger(1, data)); + } + return KeyFactory.getInstance(keyAlgorithm). + generatePublic(keySpec); + } + + private SecretKey DH(String alg, PrivateKey skE, PublicKey pkR) + throws NoSuchAlgorithmException, InvalidKeyException { + KeyAgreement ka = KeyAgreement.getInstance(kaAlgorithm); + ka.init(skE); + ka.doPhase(pkR, true); + return ka.generateSecret(alg); + } + } +} diff --git a/src/java.base/share/classes/sun/security/ssl/Hybrid.java b/src/java.base/share/classes/sun/security/ssl/Hybrid.java new file mode 100644 index 000000000000..e3e2cfa0b238 --- /dev/null +++ b/src/java.base/share/classes/sun/security/ssl/Hybrid.java @@ -0,0 +1,474 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.security.ssl; + +import sun.security.util.ArrayUtil; +import sun.security.util.CurveDB; +import sun.security.util.ECUtil; +import sun.security.util.RawKeySpec; +import sun.security.x509.X509Key; + +import javax.crypto.DecapsulateException; +import javax.crypto.KEM; +import javax.crypto.KEMSpi; +import javax.crypto.SecretKey; +import java.math.BigInteger; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyFactorySpi; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.KeyPairGeneratorSpi; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.ProviderException; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.spec.*; +import java.util.Arrays; +import java.util.Locale; + +// The Hybrid class wraps two underlying algorithms (left and right sides) +// in a single TLS hybrid named group. +// It implements: +// - Hybrid KeyPair generation +// - Hybrid KeyFactory for decoding concatenated hybrid public keys +// - Hybrid KEM implementation for performing encapsulation and +// decapsulation over two underlying algorithms (traditional +// algorithm and post-quantum KEM algorithm) + +public class Hybrid { + + public static final NamedParameterSpec X25519_MLKEM768 = + new NamedParameterSpec("X25519MLKEM768"); + + public static final NamedParameterSpec SECP256R1_MLKEM768 = + new NamedParameterSpec("SecP256r1MLKEM768"); + + public static final NamedParameterSpec SECP384R1_MLKEM1024 = + new NamedParameterSpec("SecP384r1MLKEM1024"); + + private static AlgorithmParameterSpec getSpec(String name) { + if (name.startsWith("secp")) { + return new ECGenParameterSpec(name); + } else { + return new NamedParameterSpec(name); + } + } + + private static KeyPairGenerator getKeyPairGenerator(String name) throws + NoSuchAlgorithmException { + if (name.startsWith("secp")) { + name = "EC"; + } + return KeyPairGenerator.getInstance(name); + } + + private static KeyFactory getKeyFactory(String name) throws + NoSuchAlgorithmException { + if (name.startsWith("secp")) { + name = "EC"; + } + return KeyFactory.getInstance(name); + } + + /** + * Returns a KEM instance for each side of the hybrid algorithm. + * For traditional key exchange algorithms, we use the DH-based KEM + * implementation provided by DHasKEM class. + * For ML-KEM post-quantum algorithms, we obtain a KEM instance + * with "ML-KEM". This is done to work with 3rd-party providers that + * only have "ML-KEM" KEM algorithm. + */ + private static KEM getKEM(String name) throws NoSuchAlgorithmException { + if (name.startsWith("secp") || name.equals("X25519")) { + return KEM.getInstance("DH", HybridProvider.PROVIDER); + } else { + return KEM.getInstance("ML-KEM"); + } + } + + public static class KeyPairGeneratorImpl extends KeyPairGeneratorSpi { + private final KeyPairGenerator left; + private final KeyPairGenerator right; + private final AlgorithmParameterSpec leftSpec; + private final AlgorithmParameterSpec rightSpec; + + public KeyPairGeneratorImpl(String leftAlg, String rightAlg) + throws NoSuchAlgorithmException { + left = getKeyPairGenerator(leftAlg); + right = getKeyPairGenerator(rightAlg); + leftSpec = getSpec(leftAlg); + rightSpec = getSpec(rightAlg); + } + + @Override + public void initialize(AlgorithmParameterSpec params, + SecureRandom random) + throws InvalidAlgorithmParameterException { + left.initialize(leftSpec, random); + right.initialize(rightSpec, random); + } + + @Override + public void initialize(int keysize, SecureRandom random) { + // NO-OP (do nothing) + } + + @Override + public KeyPair generateKeyPair() { + var kp1 = left.generateKeyPair(); + var kp2 = right.generateKeyPair(); + return new KeyPair( + new PublicKeyImpl("Hybrid", kp1.getPublic(), + kp2.getPublic()), + new PrivateKeyImpl("Hybrid", kp1.getPrivate(), + kp2.getPrivate())); + } + } + + public static class KeyFactoryImpl extends KeyFactorySpi { + private final KeyFactory left; + private final KeyFactory right; + private final int leftlen; + private final String leftname; + private final String rightname; + + public KeyFactoryImpl(String left, String right) + throws NoSuchAlgorithmException { + this.left = getKeyFactory(left); + this.right = getKeyFactory(right); + this.leftlen = leftPublicLength(left); + this.leftname = left; + this.rightname = right; + } + + @Override + protected PublicKey engineGeneratePublic(KeySpec keySpec) + throws InvalidKeySpecException { + if (keySpec == null) { + throw new InvalidKeySpecException("keySpec must not be null"); + } + + if (keySpec instanceof RawKeySpec rks) { + byte[] key = rks.getKeyArr(); + if (key == null) { + throw new InvalidKeySpecException( + "RawkeySpec contains null key data"); + } + if (key.length <= leftlen) { + throw new InvalidKeySpecException( + "Hybrid key length " + key.length + + " is too short and its left key length is " + + leftlen); + } + + byte[] leftKeyBytes = Arrays.copyOfRange(key, 0, leftlen); + byte[] rightKeyBytes = Arrays.copyOfRange(key, leftlen, + key.length); + PublicKey leftKey, rightKey; + + try { + if (leftname.startsWith("secp")) { + var curve = CurveDB.lookup(leftname); + var ecSpec = new ECPublicKeySpec( + ECUtil.decodePoint(leftKeyBytes, + curve.getCurve()), curve); + leftKey = left.generatePublic(ecSpec); + } else if (leftname.startsWith("ML-KEM")) { + leftKey = left.generatePublic(new RawKeySpec( + leftKeyBytes)); + } else { + throw new InvalidKeySpecException("Unsupported left" + + " algorithm" + leftname); + } + + if (rightname.equals("X25519")) { + ArrayUtil.reverse(rightKeyBytes); + var xecSpec = new XECPublicKeySpec( + new NamedParameterSpec(rightname), + new BigInteger(1, rightKeyBytes)); + rightKey = right.generatePublic(xecSpec); + } else if (rightname.startsWith("ML-KEM")) { + rightKey = right.generatePublic(new RawKeySpec( + rightKeyBytes)); + } else { + throw new InvalidKeySpecException("Unsupported right" + + " algorithm: " + rightname); + } + + return new PublicKeyImpl("Hybrid", leftKey, rightKey); + } catch (Exception e) { + throw new InvalidKeySpecException("Failed to decode " + + "hybrid key", e); + } + } + + throw new InvalidKeySpecException( + "KeySpec type:" + + keySpec.getClass().getName() + " not supported"); + } + + private static int leftPublicLength(String name) { + return switch (name.toLowerCase(Locale.ROOT)) { + case "secp256r1" -> 65; + case "secp384r1" -> 97; + case "ml-kem-768" -> 1184; + default -> throw new IllegalArgumentException( + "Unknown named group: " + name); + }; + } + + @Override + protected PrivateKey engineGeneratePrivate(KeySpec keySpec) throws + InvalidKeySpecException { + throw new UnsupportedOperationException(); + } + + @Override + protected T engineGetKeySpec(Key key, + Class keySpec) throws InvalidKeySpecException { + throw new UnsupportedOperationException(); + } + + @Override + protected Key engineTranslateKey(Key key) throws InvalidKeyException { + throw new UnsupportedOperationException(); + } + } + + public static class KEMImpl implements KEMSpi { + private final KEM left; + private final KEM right; + + public KEMImpl(String left, String right) + throws NoSuchAlgorithmException { + this.left = getKEM(left); + this.right = getKEM(right); + } + + @Override + public EncapsulatorSpi engineNewEncapsulator(PublicKey publicKey, + AlgorithmParameterSpec spec, SecureRandom secureRandom) throws + InvalidAlgorithmParameterException, InvalidKeyException { + if (publicKey instanceof PublicKeyImpl pk) { + return new Handler(left.newEncapsulator(pk.left, secureRandom), + right.newEncapsulator(pk.right, secureRandom), + null, null); + } + throw new InvalidKeyException(); + } + + @Override + public DecapsulatorSpi engineNewDecapsulator(PrivateKey privateKey, + AlgorithmParameterSpec spec) + throws InvalidAlgorithmParameterException, InvalidKeyException { + if (privateKey instanceof PrivateKeyImpl pk) { + return new Handler(null, null, left.newDecapsulator(pk.left), + right.newDecapsulator(pk.right)); + } + throw new InvalidKeyException(); + } + } + + private static byte[] concat(byte[]... inputs) { + int outLen = 0; + for (byte[] in : inputs) { + outLen += in.length; + } + byte[] out = new byte[outLen]; + int pos = 0; + for (byte[] in : inputs) { + System.arraycopy(in, 0, out, pos, in.length); + pos += in.length; + } + return out; + } + + private record Handler(KEM.Encapsulator le, KEM.Encapsulator re, + KEM.Decapsulator ld, KEM.Decapsulator rd) + implements KEMSpi.EncapsulatorSpi, KEMSpi.DecapsulatorSpi { + @Override + public KEM.Encapsulated engineEncapsulate(int from, int to, + String algorithm) { + int expectedSecretSize = engineSecretSize(); + if (!(from == 0 && to == expectedSecretSize)) { + throw new IllegalArgumentException( + "Invalid range for encapsulation: from = " + from + + " to = " + to + ", expected total secret size = " + + expectedSecretSize); + } + + var left = le.encapsulate(); + var right = re.encapsulate(); + return new KEM.Encapsulated( + new SecretKeyImpl(left.key(), right.key()), + concat(left.encapsulation(), right.encapsulation()), + null); + } + + @Override + public int engineSecretSize() { + if (le != null) { + return le.secretSize() + re.secretSize(); + } else { + return ld.secretSize() + rd.secretSize(); + } + } + + @Override + public int engineEncapsulationSize() { + if (le != null) { + return le.encapsulationSize() + re.encapsulationSize(); + } else { + return ld.encapsulationSize() + rd.encapsulationSize(); + } + } + + @Override + public SecretKey engineDecapsulate(byte[] encapsulation, int from, + int to, String algorithm) throws DecapsulateException { + int expectedEncSize = engineEncapsulationSize(); + if (encapsulation.length != expectedEncSize) { + throw new IllegalArgumentException( + "Invalid key encapsulation message length: " + + encapsulation.length + + ", expected = " + expectedEncSize); + } + + int expectedSecretSize = engineSecretSize(); + if (!(from == 0 && to == expectedSecretSize)) { + throw new IllegalArgumentException( + "Invalid range for decapsulation: from = " + from + + " to = " + to + ", expected total secret size = " + + expectedSecretSize); + } + + var left = Arrays.copyOf(encapsulation, ld.encapsulationSize()); + var right = Arrays.copyOfRange(encapsulation, + ld.encapsulationSize(), encapsulation.length); + return new SecretKeyImpl( + ld.decapsulate(left), + rd.decapsulate(right) + ); + } + } + + // Package-private + record SecretKeyImpl(SecretKey k1, SecretKey k2) + implements SecretKey { + @Override + public String getAlgorithm() { + return "Generic"; + } + + @Override + public String getFormat() { + return null; + } + + @Override + public byte[] getEncoded() { + return null; + } + } + + /** + * Hybrid public key combines two underlying public keys (left and right). + * Public keys can be transmitted/encoded because the hybrid protocol + * requires the public component to be sent. + */ + // Package-private + record PublicKeyImpl(String algorithm, PublicKey left, + PublicKey right) implements PublicKey { + @Override + public String getAlgorithm() { + return algorithm; + } + + // getFormat() returns "RAW" as hybrid key uses RAW concatenation + // of underlying encodings. + @Override + public String getFormat() { + return "RAW"; + } + + // getEncoded() returns the concatenation of the encoded bytes of the + // left and right public keys. + @Override + public byte[] getEncoded() { + return concat(onlyKey(left), onlyKey(right)); + } + + static byte[] onlyKey(PublicKey key) { + if (key instanceof X509Key xk) { + return xk.getKeyAsBytes(); + } + + // Fallback for 3rd-party providers + if (!"X.509".equalsIgnoreCase(key.getFormat())) { + throw new ProviderException("Invalid public key encoding " + + "format"); + } + var xk = new X509Key(); + try { + xk.decode(key.getEncoded()); + } catch (InvalidKeyException e) { + throw new ProviderException("Invalid public key encoding", e); + } + return xk.getKeyAsBytes(); + } + } + + /** + * Hybrid private key combines two underlying private keys (left and right). + * It is for internal use only. The private keys should never be exported. + */ + private record PrivateKeyImpl(String algorithm, PrivateKey left, + PrivateKey right) implements PrivateKey { + + @Override + public String getAlgorithm() { + return algorithm; + } + + // getFormat() returns null because there is no standard + // format for a hybrid private key. + @Override + public String getFormat() { + return null; + } + + // getEncoded() returns an empty byte array because there is no + // standard encoding format for a hybrid private key. + @Override + public byte[] getEncoded() { + return null; + } + } +} diff --git a/src/java.base/share/classes/sun/security/ssl/HybridProvider.java b/src/java.base/share/classes/sun/security/ssl/HybridProvider.java new file mode 100644 index 000000000000..64aa6c67be0e --- /dev/null +++ b/src/java.base/share/classes/sun/security/ssl/HybridProvider.java @@ -0,0 +1,141 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.security.ssl; + +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.Provider; +import java.security.NoSuchAlgorithmException; +import java.util.List; +import java.util.Map; + +import static sun.security.util.SecurityConstants.PROVIDER_VER; + +// This is an internal provider used in the JSSE code for DH-as-KEM +// and Hybrid KEM support. It doesn't actually get installed in the +// system's list of security providers that is searched at runtime. +// JSSE loads this provider internally. +// It registers Hybrid KeyPairGenerator, KeyFactory, and KEM +// implementations for hybrid named groups as Provider services. + +public class HybridProvider { + + public static final Provider PROVIDER = new ProviderImpl(); + + private static final class ProviderImpl extends Provider { + @java.io.Serial + private static final long serialVersionUID = 0L; + + // Needed for the SecurityManager. + @SuppressWarnings("removal") + ProviderImpl() { + super("HybridAndDHAsKEM", PROVIDER_VER, + "Hybrid and DHAsKEM provider"); + AccessController.doPrivileged((PrivilegedAction) () -> { + putProperties(); + return null; + }); + } + + private void putProperties() { + put("KEM.DH", DHasKEM.class.getName()); + + // Hybrid KeyPairGenerator/KeyFactory/KEM + + // The order of shares in the concatenation for group name + // X25519MLKEM768 has been reversed as per the current + // draft RFC. + var attrs = Map.of("name", "X25519MLKEM768", "left", "ML-KEM-768", + "right", "X25519"); + putService(new HybridService(this, "KeyPairGenerator", + "X25519MLKEM768", + "sun.security.ssl.Hybrid$KeyPairGeneratorImpl", + null, attrs)); + putService(new HybridService(this, "KEM", + "X25519MLKEM768", + "sun.security.ssl.Hybrid$KEMImpl", + null, attrs)); + putService(new HybridService(this, "KeyFactory", + "X25519MLKEM768", + "sun.security.ssl.Hybrid$KeyFactoryImpl", + null, attrs)); + + attrs = Map.of("name", "SecP256r1MLKEM768", "left", "secp256r1", + "right", "ML-KEM-768"); + putService(new HybridService(this, "KeyPairGenerator", + "SecP256r1MLKEM768", + "sun.security.ssl.Hybrid$KeyPairGeneratorImpl", + null, attrs)); + putService(new HybridService(this, "KEM", + "SecP256r1MLKEM768", + "sun.security.ssl.Hybrid$KEMImpl", + null, attrs)); + putService(new HybridService(this, "KeyFactory", + "SecP256r1MLKEM768", + "sun.security.ssl.Hybrid$KeyFactoryImpl", + null, attrs)); + + attrs = Map.of("name", "SecP384r1MLKEM1024", "left", "secp384r1", + "right", "ML-KEM-1024"); + putService(new HybridService(this, "KeyPairGenerator", + "SecP384r1MLKEM1024", + "sun.security.ssl.Hybrid$KeyPairGeneratorImpl", + null, attrs)); + putService(new HybridService(this, "KEM", + "SecP384r1MLKEM1024", + "sun.security.ssl.Hybrid$KEMImpl", + null, attrs)); + putService(new HybridService(this, "KeyFactory", + "SecP384r1MLKEM1024", + "sun.security.ssl.Hybrid$KeyFactoryImpl", + null, attrs)); + } + } + + private static class HybridService extends Provider.Service { + + HybridService(Provider p, String type, String algo, String cn, + List aliases, Map attrs) { + super(p, type, algo, cn, aliases, attrs); + } + + @Override + public Object newInstance(Object ctrParamObj) + throws NoSuchAlgorithmException { + String type = getType(); + return switch (type) { + case "KeyPairGenerator" -> new Hybrid.KeyPairGeneratorImpl( + getAttribute("left"), getAttribute("right")); + case "KeyFactory" -> new Hybrid.KeyFactoryImpl( + getAttribute("left"), getAttribute("right")); + case "KEM" -> new Hybrid.KEMImpl( + getAttribute("left"), getAttribute("right")); + default -> throw new NoSuchAlgorithmException( + "Unexpected value: " + type); + }; + } + } +} diff --git a/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java b/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java index b76da75c763c..99d4c43f8dc3 100644 --- a/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java +++ b/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java @@ -24,15 +24,22 @@ */ package sun.security.ssl; +import sun.security.util.RawKeySpec; + +import javax.crypto.KEM; import javax.crypto.KeyAgreement; import javax.crypto.SecretKey; import javax.crypto.spec.SecretKeySpec; import javax.net.ssl.SSLHandshakeException; import java.io.IOException; import java.security.GeneralSecurityException; +import java.security.KeyFactory; import java.security.PrivateKey; +import java.security.Provider; import java.security.PublicKey; import java.security.spec.AlgorithmParameterSpec; +import java.security.SecureRandom; +import java.util.Arrays; /** * A common class for creating various KeyDerivation types. @@ -43,15 +50,32 @@ public class KAKeyDerivation implements SSLKeyDerivation { private final HandshakeContext context; private final PrivateKey localPrivateKey; private final PublicKey peerPublicKey; + private final byte[] keyshare; + private final Provider provider; + // Constructor called by Key Agreement KAKeyDerivation(String algorithmName, HandshakeContext context, PrivateKey localPrivateKey, PublicKey peerPublicKey) { + this(algorithmName, null, context, localPrivateKey, + peerPublicKey, null); + } + + // When the constructor called by KEM: store the client's public key or the + // encapsulated message in keyshare. + KAKeyDerivation(String algorithmName, + NamedGroup namedGroup, + HandshakeContext context, + PrivateKey localPrivateKey, + PublicKey peerPublicKey, + byte[] keyshare) { this.algorithmName = algorithmName; this.context = context; this.localPrivateKey = localPrivateKey; this.peerPublicKey = peerPublicKey; + this.keyshare = keyshare; + this.provider = (namedGroup != null) ? namedGroup.getProvider() : null; } @Override @@ -92,20 +116,14 @@ private SecretKey t12DeriveKey(String algorithm, } } - /** - * Handle the TLSv1.3 objects, which use the HKDF algorithms. - */ - private SecretKey t13DeriveKey(String algorithm, - AlgorithmParameterSpec params) throws IOException { + private SecretKey deriveHandshakeSecret(String label, + SecretKey sharedSecret) + throws GeneralSecurityException, IOException { + SecretKey earlySecret = null; + SecretKey saltSecret = null; + CipherSuite.HashAlg hashAlg = context.negotiatedCipherSuite.hashAlg; + SSLKeyDerivation kd = context.handshakeKeyDerivation; try { - KeyAgreement ka = KeyAgreement.getInstance(algorithmName); - ka.init(localPrivateKey); - ka.doPhase(peerPublicKey, true); - SecretKey sharedSecret - = ka.generateSecret("TlsPremasterSecret"); - - CipherSuite.HashAlg hashAlg = context.negotiatedCipherSuite.hashAlg; - SSLKeyDerivation kd = context.handshakeKeyDerivation; HKDF hkdf = new HKDF(hashAlg.name); if (kd == null) { // No PSK is in use. // If PSK is not in use Early Secret will still be @@ -113,16 +131,106 @@ private SecretKey t13DeriveKey(String algorithm, byte[] zeros = new byte[hashAlg.hashLength]; SecretKeySpec ikm = new SecretKeySpec(zeros, "TlsPreSharedSecret"); - SecretKey earlySecret + earlySecret = hkdf.extract(zeros, ikm, "TlsEarlySecret"); kd = new SSLSecretDerivation(context, earlySecret); } // derive salt secret - SecretKey saltSecret = kd.deriveKey("TlsSaltSecret", null); + saltSecret = kd.deriveKey("TlsSaltSecret", null); // derive handshake secret - return hkdf.extract(saltSecret, sharedSecret, algorithm); + if (sharedSecret instanceof Hybrid.SecretKeyImpl hsk) { + // No javax.crypto.KDF. Concatenating the two hybrid + // shared secrets for single IKM in HKDF.extract(), + // then clearing the temporary copies. + byte[] k1 = hsk.k1().getEncoded(); + byte[] k2 = hsk.k2().getEncoded(); + byte[] ikm = new byte[k1.length + k2.length]; + System.arraycopy(k1, 0, ikm, 0, k1.length); + System.arraycopy(k2, 0, ikm, k1.length, k2.length); + try { + return hkdf.extract(saltSecret, + new SecretKeySpec(ikm, "TlsPremasterSecret"), + label); + } finally { + Arrays.fill(k1, (byte)0); + Arrays.fill(k2, (byte)0); + Arrays.fill(ikm, (byte)0); + } + } else { + return hkdf.extract(saltSecret, sharedSecret, label); + } + } catch (GeneralSecurityException gse) { + throw new SSLHandshakeException("Could not generate secret", gse); + } + } + /** + * This method is called by the server to perform KEM encapsulation. + * It uses the client's public key (sent by the client as a keyshare) + * to encapsulate a shared secret and returns the encapsulated message. + * + * Package-private, used from KeyShareExtension.SHKeyShareProducer:: + * produce(). + */ + KEM.Encapsulated encapsulate(String algorithm, SecureRandom random) + throws IOException { + SecretKey sharedSecret = null; + + if (keyshare == null) { + throw new IOException("No keyshare available for KEM " + + "encapsulation"); + } + + try { + KeyFactory kf = (provider != null) ? + KeyFactory.getInstance(algorithmName, provider) : + KeyFactory.getInstance(algorithmName); + var pk = kf.generatePublic(new RawKeySpec(keyshare)); + + KEM kem = (provider != null) ? + KEM.getInstance(algorithmName, provider) : + KEM.getInstance(algorithmName); + KEM.Encapsulator e = kem.newEncapsulator(pk, random); + KEM.Encapsulated enc = e.encapsulate(); + sharedSecret = enc.key(); + + SecretKey derived = deriveHandshakeSecret(algorithm, sharedSecret); + + return new KEM.Encapsulated(derived, enc.encapsulation(), null); + } catch (GeneralSecurityException gse) { + throw new SSLHandshakeException("Could not generate secret", gse); + } + } + + /** + * Handle the TLSv1.3 objects, which use the HKDF algorithms. + */ + private SecretKey t13DeriveKey(String type, + AlgorithmParameterSpec params) throws IOException { + SecretKey sharedSecret = null; + + try { + if (keyshare != null) { + // Using KEM: called by the client after receiving the KEM + // ciphertext (keyshare) from the server in ServerHello. + // The client decapsulates it using its private key. + KEM kem = (provider != null) + ? KEM.getInstance(algorithmName, provider) + : KEM.getInstance(algorithmName); + var decapsulator = kem.newDecapsulator(localPrivateKey); + sharedSecret = decapsulator.decapsulate( + keyshare, 0, decapsulator.secretSize(), + "TlsPremasterSecret"); + } else { + // Using traditional DH-style Key Agreement + KeyAgreement ka = KeyAgreement.getInstance(algorithmName); + ka.init(localPrivateKey); + ka.doPhase(peerPublicKey, true); + sharedSecret = ka.generateSecret("TlsPremasterSecret"); + } + + return deriveHandshakeSecret(type, sharedSecret); } catch (GeneralSecurityException gse) { throw new SSLHandshakeException("Could not generate secret", gse); } diff --git a/src/java.base/share/classes/sun/security/ssl/KEMKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/KEMKeyExchange.java new file mode 100644 index 000000000000..fb8de6cb104e --- /dev/null +++ b/src/java.base/share/classes/sun/security/ssl/KEMKeyExchange.java @@ -0,0 +1,223 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package sun.security.ssl; + +import java.io.IOException; +import java.security.GeneralSecurityException; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Provider; +import java.security.ProviderException; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.spec.NamedParameterSpec; +import javax.crypto.SecretKey; + +import sun.security.ssl.NamedGroup.NamedGroupSpec; +import sun.security.x509.X509Key; + +/** + * Specifics for single or hybrid Key exchanges based on KEM + */ +final class KEMKeyExchange { + + static final SSLKeyAgreementGenerator kemKAGenerator + = new KEMKAGenerator(); + + static final class KEMCredentials implements NamedGroupCredentials { + + final NamedGroup namedGroup; + // Unlike other credentials, we directly store the key share + // value here, no need to convert to a key + private final byte[] keyshare; + + KEMCredentials(byte[] keyshare, NamedGroup namedGroup) { + this.keyshare = keyshare; + this.namedGroup = namedGroup; + } + + // For KEM, server performs encapsulation and the resulting + // encapsulated message becomes the key_share value sent to + // the client. It is not a public key, so no PublicKey object + // to return. + @Override + public PublicKey getPublicKey() { + throw new UnsupportedOperationException( + "KEMCredentials stores raw keyshare, not a PublicKey"); + } + + public byte[] getKeyShare() { + return keyshare; + } + + @Override + public NamedGroup getNamedGroup() { + return namedGroup; + } + + /** + * Instantiates a KEMCredentials object + */ + static KEMCredentials valueOf(NamedGroup namedGroup, + byte[] encodedPoint) { + + if (namedGroup.spec != NamedGroupSpec.NAMED_GROUP_KEM) { + throw new RuntimeException( + "Credentials decoding: Not KEM named group"); + } + + if (encodedPoint == null || encodedPoint.length == 0) { + return null; + } + + return new KEMCredentials(encodedPoint, namedGroup); + } + } + + private static class KEMPossession implements SSLPossession { + private final NamedGroup namedGroup; + + public KEMPossession(NamedGroup ng) { + this.namedGroup = ng; + } + public NamedGroup getNamedGroup() { + return namedGroup; + } + } + + static final class KEMReceiverPossession extends KEMPossession { + + private final PrivateKey privateKey; + private final PublicKey publicKey; + + KEMReceiverPossession(NamedGroup namedGroup, SecureRandom random) { + super(namedGroup); + String algName = null; + try { + // For KEM: This receiver side (client) generates a key pair. + algName = ((NamedParameterSpec)namedGroup.keAlgParamSpec). + getName(); + Provider provider = namedGroup.getProvider(); + KeyPairGenerator kpg = (provider != null) ? + KeyPairGenerator.getInstance(algName, provider) : + KeyPairGenerator.getInstance(algName); + + kpg.initialize(namedGroup.keAlgParamSpec, random); + KeyPair kp = kpg.generateKeyPair(); + privateKey = kp.getPrivate(); + publicKey = kp.getPublic(); + } catch (GeneralSecurityException e) { + throw new RuntimeException( + "Could not generate keypair for algorithm: " + + algName, e); + } + } + + @Override + public byte[] encode() { + if (publicKey instanceof X509Key xk) { + return xk.getKeyAsBytes(); + } else if (publicKey instanceof Hybrid.PublicKeyImpl hk) { + return hk.getEncoded(); + } + throw new ProviderException("Unsupported key type: " + publicKey); + } + + // Package-private + PublicKey getPublicKey() { + return publicKey; + } + + // Package-private + PrivateKey getPrivateKey() { + return privateKey; + } + } + + static final class KEMSenderPossession extends KEMPossession { + + private SecretKey key; + private final SecureRandom random; + + KEMSenderPossession(NamedGroup namedGroup, SecureRandom random) { + super(namedGroup); + this.random = random; + } + + // Package-private + SecureRandom getRandom() { + return random; + } + + // Package-private + SecretKey getKey() { + return key; + } + + // Package-private + void setKey(SecretKey key) { + this.key = key; + } + + @Override + public byte[] encode() { + throw new UnsupportedOperationException("encode() not supported"); + } + } + + private static final class KEMKAGenerator + implements SSLKeyAgreementGenerator { + + // Prevent instantiation of this class. + private KEMKAGenerator() { + // blank + } + + @Override + public SSLKeyDerivation createKeyDerivation( + HandshakeContext context) throws IOException { + for (SSLPossession poss : context.handshakePossessions) { + if (poss instanceof KEMReceiverPossession kposs) { + NamedGroup ng = kposs.getNamedGroup(); + for (SSLCredentials cred : context.handshakeCredentials) { + if (cred instanceof KEMCredentials kcred && + ng.equals(kcred.namedGroup)) { + String name = ((NamedParameterSpec) + ng.keAlgParamSpec).getName(); + return new KAKeyDerivation(name, ng, context, + kposs.getPrivateKey(), null, + kcred.getKeyShare()); + } + } + } + } + context.conContext.fatal(Alert.HANDSHAKE_FAILURE, + "No suitable KEM key agreement " + + "parameters negotiated"); + return null; + } + } +} diff --git a/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java b/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java index 98e4693e9170..5465c73d3e9e 100644 --- a/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java +++ b/src/java.base/share/classes/sun/security/ssl/KeyShareExtension.java @@ -27,8 +27,11 @@ import java.io.IOException; import java.nio.ByteBuffer; +import java.security.AlgorithmConstraints; import java.security.CryptoPrimitive; import java.security.GeneralSecurityException; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.NamedParameterSpec; import java.text.MessageFormat; import java.util.*; import javax.net.ssl.SSLProtocolException; @@ -297,7 +300,9 @@ private static byte[] getShare(ClientHandshakeContext chc, // update the context chc.handshakePossessions.add(pos); // May need more possession types in the future. - if (pos instanceof NamedGroupPossession) { + if (pos instanceof NamedGroupPossession || + pos instanceof + KEMKeyExchange.KEMReceiverPossession) { return pos.encode(); } } @@ -358,24 +363,16 @@ public void consume(ConnectionContext context, try { SSLCredentials kaCred = ng.decodeCredentials(entry.keyExchange); - if (shc.algorithmConstraints != null && - kaCred instanceof - NamedGroupCredentials namedGroupCredentials) { - if (!shc.algorithmConstraints.permits( - EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), - namedGroupCredentials.getPublicKey())) { - if (SSLLogger.isOn && - SSLLogger.isOn("ssl,handshake")) { - SSLLogger.warning( - "key share entry of " + ng + " does not " + - " comply with algorithm constraints"); - } - kaCred = null; + if (!isCredentialPermitted(shc.algorithmConstraints, + kaCred)) { + if (SSLLogger.isOn && + SSLLogger.isOn("ssl,handshake")) { + SSLLogger.warning( + "key share entry of " + ng + " does not " + + "comply with algorithm constraints"); } - } - - if (kaCred != null) { + } else { credentials.add(kaCred); } } catch (GeneralSecurityException ex) { @@ -513,7 +510,8 @@ private SHKeyShareProducer() { @Override public byte[] produce(ConnectionContext context, HandshakeMessage message) throws IOException { - // The producing happens in client side only. + // The producing happens in server side only. + ServerHandshakeContext shc = (ServerHandshakeContext)context; // In response to key_share request only @@ -571,7 +569,9 @@ public byte[] produce(ConnectionContext context, SSLPossession[] poses = ke.createPossessions(shc); for (SSLPossession pos : poses) { - if (!(pos instanceof NamedGroupPossession)) { + if (!(pos instanceof NamedGroupPossession || + pos instanceof + KEMKeyExchange.KEMSenderPossession)) { // May need more possession types in the future. continue; } @@ -579,7 +579,34 @@ public byte[] produce(ConnectionContext context, // update the context shc.handshakeKeyExchange = ke; shc.handshakePossessions.add(pos); - keyShare = new KeyShareEntry(ng.id, pos.encode()); + + // For KEM, perform encapsulation using the client's public + // key (KEMCredentials). The resulting encapsulated message + // becomes the key_share value sent to the client. The + // shared secret derived from encapsulation is stored in + // the KEMSenderPossession for later use in the TLS key + // schedule. + + // SSLKeyExchange.createPossessions() returns at most one + // key-agreement possession or one KEMSenderPossession + // per handshake. + if (pos instanceof KEMKeyExchange.KEMSenderPossession xp) { + if (cd instanceof KEMKeyExchange.KEMCredentials kcred + && ng.equals(kcred.namedGroup)) { + String name = ((NamedParameterSpec) + ng.keAlgParamSpec).getName(); + KAKeyDerivation handshakeKD = new KAKeyDerivation( + name, ng, shc, null, null, + kcred.getKeyShare()); + var encaped = handshakeKD.encapsulate( + "TlsHandshakeSecret", xp.getRandom()); + xp.setKey(encaped.key()); + keyShare = new KeyShareEntry(ng.id, + encaped.encapsulation()); + } + } else { + keyShare = new KeyShareEntry(ng.id, pos.encode()); + } break; } @@ -663,19 +690,13 @@ public void consume(ConnectionContext context, try { SSLCredentials kaCred = ng.decodeCredentials(keyShare.keyExchange); - if (chc.algorithmConstraints != null && - kaCred instanceof - NamedGroupCredentials namedGroupCredentials) { - if (!chc.algorithmConstraints.permits( - EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), - namedGroupCredentials.getPublicKey())) { - chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, - "key share entry of " + ng + " does not " + - " comply with algorithm constraints"); - } - } - if (kaCred != null) { + if (!isCredentialPermitted(chc.algorithmConstraints, + kaCred)) { + chc.conContext.fatal(Alert.INSUFFICIENT_SECURITY, + "key share entry of " + ng + " does not " + + "comply with algorithm constraints"); + } else { credentials = kaCred; } } catch (GeneralSecurityException ex) { @@ -696,6 +717,34 @@ public void consume(ConnectionContext context, } } + private static boolean isCredentialPermitted( + AlgorithmConstraints constraints, + SSLCredentials cred) { + + if (constraints == null) return true; + if (cred == null) return false; + + if (cred instanceof NamedGroupCredentials namedGroupCred) { + if (namedGroupCred instanceof KEMKeyExchange.KEMCredentials + kemCred) { + AlgorithmParameterSpec paramSpec = kemCred.getNamedGroup(). + keAlgParamSpec; + String algName = (paramSpec instanceof NamedParameterSpec nps) ? + nps.getName() : null; + return algName != null && constraints.permits( + EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), + algName, + null); + } else { + return constraints.permits( + EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), + namedGroupCred.getPublicKey()); + } + } + + return true; + } + /** * The absence processing if the extension is not present in * the ServerHello handshake message. diff --git a/src/java.base/share/classes/sun/security/ssl/NamedGroup.java b/src/java.base/share/classes/sun/security/ssl/NamedGroup.java index 2a6c966a2543..816b31ecfce7 100644 --- a/src/java.base/share/classes/sun/security/ssl/NamedGroup.java +++ b/src/java.base/share/classes/sun/security/ssl/NamedGroup.java @@ -215,6 +215,39 @@ enum NamedGroup { ProtocolVersion.PROTOCOLS_TO_13, PredefinedDHParameterSpecs.ffdheParams.get(8192)), + ML_KEM_512(0x0200, "MLKEM512", + NamedGroupSpec.NAMED_GROUP_KEM, + ProtocolVersion.PROTOCOLS_OF_13, + null), + + ML_KEM_768(0x0201, "MLKEM768", + NamedGroupSpec.NAMED_GROUP_KEM, + ProtocolVersion.PROTOCOLS_OF_13, + null), + + ML_KEM_1024(0x0202, "MLKEM1024", + NamedGroupSpec.NAMED_GROUP_KEM, + ProtocolVersion.PROTOCOLS_OF_13, + null), + + X25519MLKEM768(0x11ec, "X25519MLKEM768", + NamedGroupSpec.NAMED_GROUP_KEM, + ProtocolVersion.PROTOCOLS_OF_13, + Hybrid.X25519_MLKEM768, + HybridProvider.PROVIDER), + + SECP256R1MLKEM768(0x11eb, "SecP256r1MLKEM768", + NamedGroupSpec.NAMED_GROUP_KEM, + ProtocolVersion.PROTOCOLS_OF_13, + Hybrid.SECP256R1_MLKEM768, + HybridProvider.PROVIDER), + + SECP384R1MLKEM1024(0x11ed, "SecP384r1MLKEM1024", + NamedGroupSpec.NAMED_GROUP_KEM, + ProtocolVersion.PROTOCOLS_OF_13, + Hybrid.SECP384R1_MLKEM1024, + HybridProvider.PROVIDER), + // Elliptic Curves (RFC 4492) // // arbitrary prime and characteristic-2 curves @@ -235,22 +268,33 @@ enum NamedGroup { final AlgorithmParameterSpec keAlgParamSpec; final AlgorithmParameters keAlgParams; final boolean isAvailable; + final Provider defaultProvider; // performance optimization private static final Set KEY_AGREEMENT_PRIMITIVE_SET = Collections.unmodifiableSet(EnumSet.of(CryptoPrimitive.KEY_AGREEMENT)); - // Constructor used for all NamedGroup types NamedGroup(int id, String name, NamedGroupSpec namedGroupSpec, ProtocolVersion[] supportedProtocols, AlgorithmParameterSpec keAlgParamSpec) { + this(id, name, namedGroupSpec, supportedProtocols, keAlgParamSpec, + null); + } + + // Constructor used for all NamedGroup types + NamedGroup(int id, String name, + NamedGroupSpec namedGroupSpec, + ProtocolVersion[] supportedProtocols, + AlgorithmParameterSpec keAlgParamSpec, + Provider defaultProvider) { this.id = id; this.name = name; this.spec = namedGroupSpec; this.algorithm = namedGroupSpec.algorithm; this.supportedProtocols = supportedProtocols; this.keAlgParamSpec = keAlgParamSpec; + this.defaultProvider = defaultProvider; // Check if it is a supported named group. AlgorithmParameters algParams = null; @@ -267,16 +311,28 @@ enum NamedGroup { // Check the specific algorithm parameters. if (mediator) { try { - algParams = - AlgorithmParameters.getInstance(namedGroupSpec.algorithm); - algParams.init(keAlgParamSpec); + // Skip AlgorithmParameters for KEMs (not supported) + // Check KEM's availability via KeyFactory + if (namedGroupSpec == NamedGroupSpec.NAMED_GROUP_KEM) { + if (defaultProvider == null) { + KeyFactory.getInstance(name); + } else { + KeyFactory.getInstance(name, defaultProvider); + } + } else { + // ECDHE or others: use AlgorithmParameters as before + algParams = AlgorithmParameters.getInstance( + namedGroupSpec.algorithm); + algParams.init(keAlgParamSpec); + } } catch (InvalidParameterSpecException | NoSuchAlgorithmException exp) { if (namedGroupSpec != NamedGroupSpec.NAMED_GROUP_XDH) { mediator = false; if (SSLLogger.isOn && SSLLogger.isOn("ssl,handshake")) { SSLLogger.warning( - "No AlgorithmParameters for " + name, exp); + "No AlgorithmParameters or KeyFactory for " + name, + exp); } } else { // Please remove the following code if the XDH/X25519/X448 @@ -308,6 +364,10 @@ enum NamedGroup { this.keAlgParams = mediator ? algParams : null; } + Provider getProvider() { + return defaultProvider; + } + // // The next set of methods search & retrieve NamedGroups. // @@ -546,6 +606,10 @@ SSLCredentials decodeCredentials( return spec.decodeCredentials(this, encoded); } + SSLPossession createPossession(boolean isClient, SecureRandom random) { + return spec.createPossession(this, isClient, random); + } + SSLPossession createPossession(SecureRandom random) { return spec.createPossession(this, random); } @@ -567,6 +631,11 @@ SSLCredentials decodeCredentials(NamedGroup ng, SSLKeyDerivation createKeyDerivation( HandshakeContext hc) throws IOException; + + default SSLPossession createPossession(NamedGroup ng, boolean isClient, + SecureRandom random) { + return createPossession(ng, random); + } } enum NamedGroupSpec implements NamedGroupScheme { @@ -579,6 +648,10 @@ enum NamedGroupSpec implements NamedGroupScheme { // Finite Field Groups (XDH) NAMED_GROUP_XDH("XDH", XDHScheme.instance), + // Post-Quantum Cryptography (PQC) KEM groups + // Currently used for hybrid named groups + NAMED_GROUP_KEM("KEM", KEMScheme.instance), + // arbitrary prime and curves (ECDHE) NAMED_GROUP_ARBITRARY("EC", null), @@ -635,6 +708,15 @@ public SSLCredentials decodeCredentials(NamedGroup ng, return null; } + public SSLPossession createPossession( + NamedGroup ng, boolean isClient, SecureRandom random) { + if (scheme != null) { + return scheme.createPossession(ng, isClient, random); + } + + return null; + } + @Override public SSLPossession createPossession( NamedGroup ng, SecureRandom random) { @@ -740,6 +822,42 @@ public SSLKeyDerivation createKeyDerivation( } } + private static class KEMScheme implements NamedGroupScheme { + private static final KEMScheme instance = new KEMScheme(); + + @Override + public byte[] encodePossessionPublicKey(NamedGroupPossession poss) { + return poss.encode(); + } + + @Override + public SSLCredentials decodeCredentials(NamedGroup ng, + byte[] encoded) throws IOException, GeneralSecurityException { + return KEMKeyExchange.KEMCredentials.valueOf(ng, encoded); + } + + @Override + public SSLPossession createPossession(NamedGroup ng, + SecureRandom random) { + // Must call createPossession with isClient + throw new UnsupportedOperationException(); + } + + @Override + public SSLPossession createPossession( + NamedGroup ng, boolean isClient, SecureRandom random) { + return isClient + ? new KEMKeyExchange.KEMReceiverPossession(ng, random) + : new KEMKeyExchange.KEMSenderPossession(ng, random); + } + + @Override + public SSLKeyDerivation createKeyDerivation( + HandshakeContext hc) throws IOException { + return KEMKeyExchange.kemKAGenerator.createKeyDerivation(hc); + } + } + static final class SupportedGroups { // the supported named groups, non-null immutable list static final String[] namedGroups; @@ -786,6 +904,9 @@ static final class SupportedGroups { } else { // default groups NamedGroup[] groups = new NamedGroup[] { + // Hybrid key agreement + X25519MLKEM768, + // Primary XDH (RFC 7748) curves X25519, diff --git a/src/java.base/share/classes/sun/security/ssl/SSLKeyExchange.java b/src/java.base/share/classes/sun/security/ssl/SSLKeyExchange.java index 22a44590ce3c..263308f0659f 100644 --- a/src/java.base/share/classes/sun/security/ssl/SSLKeyExchange.java +++ b/src/java.base/share/classes/sun/security/ssl/SSLKeyExchange.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -570,7 +570,9 @@ static T13KeyAgreement valueOf(NamedGroup namedGroup) { @Override public SSLPossession createPossession(HandshakeContext hc) { - return namedGroup.createPossession(hc.sslContext.getSecureRandom()); + return namedGroup.createPossession( + hc instanceof ClientHandshakeContext, + hc.sslContext.getSecureRandom()); } @Override diff --git a/src/java.base/share/classes/sun/security/ssl/ServerHello.java b/src/java.base/share/classes/sun/security/ssl/ServerHello.java index 36177cf6acff..e4b3d38c7db1 100644 --- a/src/java.base/share/classes/sun/security/ssl/ServerHello.java +++ b/src/java.base/share/classes/sun/security/ssl/ServerHello.java @@ -558,6 +558,34 @@ public byte[] produce(ConnectionContext context, clientHello); shc.serverHelloRandom = shm.serverRandom; + // For key derivation, we will either use the traditional Key + // Agreement (KA) model or the Key Encapsulation Mechanism (KEM) + // model, depending on what key exchange group is used. + // + // For KA flows, the server first receives the client's share, + // then generates its key share, and finally comes here. + // However, this is changed for KEM: the server + // must perform both actions - derive the secret and generate + // the key encapsulation message at the same time during + // encapsulation in SHKeyShareProducer. + // + // Traditional Key Agreement (KA): + // - Both peers generate a key share and exchange it. + // - Each peer computes a shared secret sometime after + // receiving the other's key share. + // + // Key Encapsulation Mechanism (KEM): + // The client publishes a public key via a KeyShareExtension, + // which the server uses to: + // + // - generate the shared secret + // - encapsulate the message which is sent to the client in + // another KeyShareExtension + // + // The derived shared secret must be stored in a + // KEMSenderPossession so it can be retrieved for handshake + // traffic secret derivation later. + // Produce extensions for ServerHello handshake message. SSLExtension[] serverHelloExtensions = shc.sslConfig.getEnabledExtensions( @@ -583,9 +611,26 @@ public byte[] produce(ConnectionContext context, "Not negotiated key shares"); } - SSLKeyDerivation handshakeKD = ke.createKeyDerivation(shc); - SecretKey handshakeSecret = handshakeKD.deriveKey( - "TlsHandshakeSecret", null); + SecretKey handshakeSecret = null; + + // For KEM, the shared secret has already been generated and + // stored in the server's possession (KEMSenderPossession) + // during encapsulation in SHKeyShareProducer. + // + // Only one key share is selected by the server, so at most one + // possession will contain the pre-derived shared secret. + for (var pos : shc.handshakePossessions) { + if (pos instanceof KEMKeyExchange.KEMSenderPossession xp) { + handshakeSecret = xp.getKey(); + break; + } + } + + if (handshakeSecret == null) { + SSLKeyDerivation handshakeKD = ke.createKeyDerivation(shc); + handshakeSecret = handshakeKD.deriveKey( + "TlsHandshakeSecret", null); + } SSLTrafficKeyDerivation kdg = SSLTrafficKeyDerivation.valueOf(shc.negotiatedProtocol); diff --git a/src/java.base/share/classes/sun/security/x509/X509Key.java b/src/java.base/share/classes/sun/security/x509/X509Key.java index 0dccc3d33f08..c712b28456d9 100644 --- a/src/java.base/share/classes/sun/security/x509/X509Key.java +++ b/src/java.base/share/classes/sun/security/x509/X509Key.java @@ -142,6 +142,12 @@ protected BitArray getKey() { return (BitArray)bitStringKey.clone(); } + public byte[] getKeyAsBytes() { + // Using 'getKey()` here over `bitStringKey` as the bitStringKey + // might not be set yet. + return getKey().toByteArray(); + } + /** * Construct X.509 subject public key from a DER value. If * the runtime environment is configured with a specific class for diff --git a/test/jdk/javax/net/ssl/SSLParameters/NamedGroups.java b/test/jdk/javax/net/ssl/SSLParameters/NamedGroups.java index 25f73606b967..786b907b79a1 100644 --- a/test/jdk/javax/net/ssl/SSLParameters/NamedGroups.java +++ b/test/jdk/javax/net/ssl/SSLParameters/NamedGroups.java @@ -1,4 +1,5 @@ /* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. * Copyright (C) 2022, Tencent. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -26,7 +27,7 @@ /* * @test - * @bug 8281236 + * @bug 8281236 8314323 * @summary Check TLS connection behaviors for named groups configuration * @library /javax/net/ssl/templates * @run main/othervm NamedGroups @@ -136,6 +137,60 @@ public static void main(String[] args) throws Exception { "secp256r1" }, true); + + runTest(new String[] { + "X25519MLKEM768" + }, + new String[] { + "X25519MLKEM768" + }, + false); + + runTest(new String[] { + "SecP256r1MLKEM768" + }, + new String[] { + "SecP256r1MLKEM768" + }, + false); + + runTest(new String[] { + "SecP384r1MLKEM1024" + }, + new String[] { + "SecP384r1MLKEM1024" + }, + false); + + runTest(new String[] { + "X25519MLKEM768" + }, + new String[] { + "SecP256r1MLKEM768" + }, + true); + + runTest(new String[] { + "X25519MLKEM768" + }, + new String[0], + true); + + runTest(new String[] { + "SecP256r1MLKEM768" + }, + null, + true); + + runTest(new String[] { + "X25519MLKEM768", + "x25519" + }, + new String[] { + "X25519MLKEM768", + "x25519" + }, + false); } private static void runTest(String[] serverNamedGroups, diff --git a/test/jdk/javax/net/ssl/TLSCommon/NamedGroup.java b/test/jdk/javax/net/ssl/TLSCommon/NamedGroup.java index ec89fe0d5b5e..432a2bd1b0db 100644 --- a/test/jdk/javax/net/ssl/TLSCommon/NamedGroup.java +++ b/test/jdk/javax/net/ssl/TLSCommon/NamedGroup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,7 +37,11 @@ public enum NamedGroup { FFDHE3072("ffdhe3072"), FFDHE4096("ffdhe4096"), FFDHE6144("ffdhe6144"), - FFDHE8192("ffdhe8192"); + FFDHE8192("ffdhe8192"), + + X25519MLKEM768("X25519MLKEM768"), + SECP256R1MLKEM768("SecP256r1MLKEM768"), + SECP384R1MLKEM1024("SecP384r1MLKEM1024"); public final String name; diff --git a/test/jdk/javax/net/ssl/TLSv13/ClientHelloKeyShares.java b/test/jdk/javax/net/ssl/TLSv13/ClientHelloKeyShares.java index 56f37a9e4f15..5cefc2ad1608 100644 --- a/test/jdk/javax/net/ssl/TLSv13/ClientHelloKeyShares.java +++ b/test/jdk/javax/net/ssl/TLSv13/ClientHelloKeyShares.java @@ -27,16 +27,21 @@ /* * @test - * @bug 8247630 + * @bug 8247630 8314323 * @summary Use two key share entries - * @run main/othervm ClientHelloKeyShares 29 23 + * @run main/othervm ClientHelloKeyShares 4588 29 * @run main/othervm -Djdk.tls.namedGroups=secp384r1,secp521r1,x448,ffdhe2048 ClientHelloKeyShares 24 30 * @run main/othervm -Djdk.tls.namedGroups=sect163k1,sect163r1,x25519 ClientHelloKeyShares 29 * @run main/othervm -Djdk.tls.namedGroups=sect163k1,sect163r1,secp256r1 ClientHelloKeyShares 23 * @run main/othervm -Djdk.tls.namedGroups=sect163k1,sect163r1,ffdhe2048,ffdhe3072,ffdhe4096 ClientHelloKeyShares 256 * @run main/othervm -Djdk.tls.namedGroups=sect163k1,ffdhe2048,x25519,secp256r1 ClientHelloKeyShares 256 29 * @run main/othervm -Djdk.tls.namedGroups=secp256r1,secp384r1,ffdhe2048,x25519 ClientHelloKeyShares 23 256 - */ + * @run main/othervm -Djdk.tls.namedGroups=X25519MLKEM768 ClientHelloKeyShares 4588 + * @run main/othervm -Djdk.tls.namedGroups=x25519,X25519MLKEM768 ClientHelloKeyShares 29 4588 + * @run main/othervm -Djdk.tls.namedGroups=SecP256r1MLKEM768,x25519 ClientHelloKeyShares 4587 29 + * @run main/othervm -Djdk.tls.namedGroups=SecP384r1MLKEM1024,secp256r1 ClientHelloKeyShares 4589 23 + * @run main/othervm -Djdk.tls.namedGroups=X25519MLKEM768,SecP256r1MLKEM768,X25519,secp256r1 ClientHelloKeyShares 4588 29 +*/ import javax.net.ssl.*; import javax.net.ssl.SSLEngineResult.*; @@ -52,10 +57,6 @@ public class ClientHelloKeyShares { private static final int HELLO_EXT_SUPP_VERS = 43; private static final int HELLO_EXT_KEY_SHARE = 51; private static final int TLS_PROT_VER_13 = 0x0304; - private static final int NG_SECP256R1 = 0x0017; - private static final int NG_SECP384R1 = 0x0018; - private static final int NG_X25519 = 0x001D; - private static final int NG_X448 = 0x001E; public static void main(String args[]) throws Exception { // Arguments to this test are an abitrary number of integer diff --git a/test/jdk/javax/net/ssl/TLSv13/HRRKeyShares.java b/test/jdk/javax/net/ssl/TLSv13/HRRKeyShares.java index 313b2c5084b0..a7a3f3eb39b5 100644 --- a/test/jdk/javax/net/ssl/TLSv13/HRRKeyShares.java +++ b/test/jdk/javax/net/ssl/TLSv13/HRRKeyShares.java @@ -27,10 +27,12 @@ /* * @test - * @bug 8247630 + * @bug 8247630 8314323 * @summary Use two key share entries * @library /test/lib - * @run main/othervm -Djdk.tls.namedGroups=x25519,secp256r1,secp384r1 HRRKeyShares + * @run main/othervm + * -Djdk.tls.namedGroups=x25519,secp256r1,secp384r1,X25519MLKEM768,SecP256r1MLKEM768,SecP384r1MLKEM1024 + * HRRKeyShares */ import java.io.ByteArrayOutputStream; @@ -63,6 +65,10 @@ public class HRRKeyShares { private static final int NG_SECP384R1 = 0x0018; private static final int NG_X25519 = 0x001D; private static final int NG_X448 = 0x001E; + private static final int NG_X25519_MLKEM768 = 0x11EC; + private static final int NG_SECP256R1_MLKEM768 = 0x11EB; + private static final int NG_SECP384R1_MLKEM1024 = 0x11ED; + private static final int NG_GC512A = 0x0026; private static final int COMP_NONE = 0; private static final int ALERT_TYPE_FATAL = 2; @@ -224,6 +230,18 @@ public static void main(String args[]) throws Exception { System.out.println("Test 4: Bad HRR using known / unasserted x448"); hrrKeyShareTest(NG_X448, false); System.out.println(); + + System.out.println("Test 5: Good HRR exchange using X25519MLKEM768"); + hrrKeyShareTest(NG_X25519_MLKEM768, true); + System.out.println(); + + System.out.println("Test 6: Good HRR exchange using SecP256r1MLKEM768"); + hrrKeyShareTest(NG_SECP256R1_MLKEM768, true); + System.out.println(); + + System.out.println("Test 7: Good HRR exchange using SecP384r1MLKEM1024"); + hrrKeyShareTest(NG_SECP384R1_MLKEM1024, true); + System.out.println(); } private static void logResult(String str, SSLEngineResult result) { @@ -334,7 +352,8 @@ private static void hrrKeyShareTest(int hrrNamedGroup, boolean expectedPass) try { // Now we're expecting to reissue the ClientHello, this time - // with a secp384r1 share. + // with a key share for the HRR requested named + // group (hrrNamedGroup). cTOs.compact(); clientResult = engine.wrap(clientOut, cTOs); logResult("client wrap: ", clientResult); diff --git a/test/jdk/sun/security/ssl/CipherSuite/DisabledCurve.java b/test/jdk/sun/security/ssl/CipherSuite/DisabledCurve.java index 26304c5df957..a13f8570f148 100644 --- a/test/jdk/sun/security/ssl/CipherSuite/DisabledCurve.java +++ b/test/jdk/sun/security/ssl/CipherSuite/DisabledCurve.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,12 +23,24 @@ /* * @test - * @bug 8246330 + * @bug 8246330 8314323 * @library /javax/net/ssl/templates /test/lib * @run main/othervm -Djdk.tls.namedGroups="secp384r1" DisabledCurve DISABLE_NONE PASS * @run main/othervm -Djdk.tls.namedGroups="secp384r1" DisabledCurve secp384r1 FAIL + * @run main/othervm -Djdk.tls.namedGroups="X25519MLKEM768" + DisabledCurve DISABLE_NONE PASS + * @run main/othervm -Djdk.tls.namedGroups="X25519MLKEM768" + DisabledCurve X25519MLKEM768 FAIL + * @run main/othervm -Djdk.tls.namedGroups="SecP256r1MLKEM768" + DisabledCurve DISABLE_NONE PASS + * @run main/othervm -Djdk.tls.namedGroups="SecP256r1MLKEM768" + DisabledCurve SecP256r1MLKEM768 FAIL + * @run main/othervm -Djdk.tls.namedGroups="SecP384r1MLKEM1024" + DisabledCurve DISABLE_NONE PASS + * @run main/othervm -Djdk.tls.namedGroups="SecP384r1MLKEM1024" + DisabledCurve SecP384r1MLKEM1024 FAIL */ import java.security.Security; import java.util.Arrays; @@ -45,8 +57,10 @@ public class DisabledCurve extends SSLSocketTemplate { private static final String[][][] protocols = { { { "TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1" }, { "TLSv1.2" } }, { { "TLSv1.2" }, { "TLSv1.3", "TLSv1.2", "TLSv1.1", "TLSv1" } }, - { { "TLSv1.2" }, { "TLSv1.2" } }, { { "TLSv1.1" }, { "TLSv1.1" } }, - { { "TLSv1" }, { "TLSv1" } } }; + { { "TLSv1.2" }, { "TLSv1.2" } }, + { { "TLSv1.1" }, { "TLSv1.1" } }, + { { "TLSv1" }, { "TLSv1" } }, + { { "TLSv1.3" }, { "TLSv1.3" } } }; @Override protected SSLContext createClientSSLContext() throws Exception { @@ -94,17 +108,36 @@ public static void main(String[] args) throws Exception { String expected = args[1]; String disabledName = ("DISABLE_NONE".equals(args[0]) ? "" : args[0]); boolean disabled = false; - if (disabledName.equals("")) { + + if (disabledName.isEmpty()) { Security.setProperty("jdk.disabled.namedCurves", ""); + Security.setProperty("jdk.certpath.disabledAlgorithms", ""); } else { disabled = true; - Security.setProperty("jdk.certpath.disabledAlgorithms", "secp384r1"); + Security.setProperty("jdk.certpath.disabledAlgorithms", disabledName); + if (!disabledName.contains("MLKEM")) { + Security.setProperty("jdk.disabled.namedCurves", disabledName); + } else { + Security.setProperty("jdk.disabled.namedCurves", ""); + } } // Re-enable TLSv1 and TLSv1.1 since test depends on it. SecurityUtils.removeFromDisabledTlsAlgs("TLSv1", "TLSv1.1"); + String namedGroups = System.getProperty("jdk.tls.namedGroups", ""); + boolean hybridGroup = namedGroups.contains("MLKEM"); + for (index = 0; index < protocols.length; index++) { + if (hybridGroup) { + String[] clientProtos = protocols[index][0]; + String[] serverProtos = protocols[index][1]; + + if (!(isTLS13(clientProtos) && isTLS13(serverProtos))) { + continue; + } + } + try { (new DisabledCurve()).run(); if (expected.equals("FAIL")) { @@ -123,4 +156,8 @@ public static void main(String[] args) throws Exception { } } + + private static boolean isTLS13(String[] protocols) { + return protocols.length == 1 && "TLSv1.3".equals(protocols[0]); + } } diff --git a/test/jdk/sun/security/ssl/CipherSuite/NamedGroupsWithCipherSuite.java b/test/jdk/sun/security/ssl/CipherSuite/NamedGroupsWithCipherSuite.java index 5732f42982c7..9080f5496835 100644 --- a/test/jdk/sun/security/ssl/CipherSuite/NamedGroupsWithCipherSuite.java +++ b/test/jdk/sun/security/ssl/CipherSuite/NamedGroupsWithCipherSuite.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,6 +21,8 @@ * questions. */ +import java.util.Arrays; +import java.util.List; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLServerSocket; import javax.net.ssl.SSLSocket; @@ -29,7 +31,7 @@ /* * @test - * @bug 8224650 8242929 + * @bug 8224650 8242929 8314323 * @library /javax/net/ssl/templates * /javax/net/ssl/TLSCommon * /test/lib @@ -44,17 +46,20 @@ * @run main/othervm NamedGroupsWithCipherSuite ffdhe4096 * @run main/othervm NamedGroupsWithCipherSuite ffdhe6144 * @run main/othervm NamedGroupsWithCipherSuite ffdhe8192 + * @run main/othervm NamedGroupsWithCipherSuite X25519MLKEM768 + * @run main/othervm NamedGroupsWithCipherSuite SecP256r1MLKEM768 + * @run main/othervm NamedGroupsWithCipherSuite SecP384r1MLKEM1024 */ public class NamedGroupsWithCipherSuite extends SSLSocketTemplate { - private static final Protocol[] PROTOCOLS = new Protocol[] { + private static final List PROTOCOLS = List.of( Protocol.TLSV1_3, Protocol.TLSV1_2, Protocol.TLSV1_1, Protocol.TLSV1 - }; + ); - private static final CipherSuite[] CIPHER_SUITES = new CipherSuite[] { + private static final List CIPHER_SUITES = List.of( CipherSuite.TLS_AES_128_GCM_SHA256, CipherSuite.TLS_AES_256_GCM_SHA384, CipherSuite.TLS_CHACHA20_POLY1305_SHA256, @@ -75,7 +80,23 @@ public class NamedGroupsWithCipherSuite extends SSLSocketTemplate { CipherSuite.TLS_DHE_RSA_WITH_AES_128_CBC_SHA, CipherSuite.TLS_DHE_RSA_WITH_AES_256_CBC_SHA256, CipherSuite.TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 - }; + ); + + private static final List HYBRID_NAMEDGROUPS = List.of( + "X25519MLKEM768", + "SecP256r1MLKEM768", + "SecP384r1MLKEM1024" + ); + + private static final List HYBRID_PROTOCOL = List.of( + Protocol.TLSV1_3 + ); + + private static final List HYBRID_CIPHER_SUITES = List.of( + CipherSuite.TLS_AES_128_GCM_SHA256, + CipherSuite.TLS_AES_256_GCM_SHA384, + CipherSuite.TLS_CHACHA20_POLY1305_SHA256 + ); private String protocol; private String cipher; @@ -151,48 +172,59 @@ public static void main(String[] args) throws Exception { // Re-enable TLSv1 and TLSv1.1 since test depends on it. SecurityUtils.removeFromDisabledTlsAlgs("TLSv1", "TLSv1.1"); - for (Protocol protocol : PROTOCOLS) { - for (CipherSuite cipherSuite : CIPHER_SUITES) { - // Named group converted to lower case just - // to satisfy Test condition + boolean hybridGroup = HYBRID_NAMEDGROUPS.contains(namedGroup); + List protocolList = hybridGroup ? + HYBRID_PROTOCOL : PROTOCOLS; + List cipherList = hybridGroup ? + HYBRID_CIPHER_SUITES : CIPHER_SUITES; + + // non-Hybrid named group converted to lower case just + // to satisfy Test condition + String normalizedGroup = hybridGroup ? + namedGroup : namedGroup.toLowerCase(); + + for (Protocol protocol : protocolList) { + for (CipherSuite cipherSuite : cipherList) { if (cipherSuite.supportedByProtocol(protocol) - && groupSupportdByCipher(namedGroup.toLowerCase(), - cipherSuite)) { + && groupSupportedByCipher(normalizedGroup, + cipherSuite)) { System.out.printf("Protocol: %s, cipher suite: %s%n", protocol, cipherSuite); - // Named group converted to lower case just - // to satisfy Test condition new NamedGroupsWithCipherSuite(protocol, - cipherSuite, namedGroup.toLowerCase()).run(); + cipherSuite, normalizedGroup).run(); } } } } - private static boolean groupSupportdByCipher(String group, + private static boolean groupSupportedByCipher(String group, CipherSuite cipherSuite) { + if (HYBRID_NAMEDGROUPS.contains(group)) { + return cipherSuite.keyExAlgorithm == null; + } + return (group.startsWith("x") - && xdhGroupSupportdByCipher(cipherSuite)) + && xdhGroupSupportedByCipher(cipherSuite)) || (group.startsWith("secp") - && ecdhGroupSupportdByCipher(cipherSuite)) + && ecdhGroupSupportedByCipher(cipherSuite)) || (group.startsWith("ffdhe") - && ffdhGroupSupportdByCipher(cipherSuite)); + && ffdhGroupSupportedByCipher(cipherSuite)); } - private static boolean xdhGroupSupportdByCipher( + private static boolean xdhGroupSupportedByCipher( CipherSuite cipherSuite) { return cipherSuite.keyExAlgorithm == null || cipherSuite.keyExAlgorithm == KeyExAlgorithm.ECDHE_RSA; } - private static boolean ecdhGroupSupportdByCipher( + private static boolean ecdhGroupSupportedByCipher( CipherSuite cipherSuite) { return cipherSuite.keyExAlgorithm == null || cipherSuite.keyExAlgorithm == KeyExAlgorithm.ECDHE_RSA || cipherSuite.keyExAlgorithm == KeyExAlgorithm.ECDHE_ECDSA; } - private static boolean ffdhGroupSupportdByCipher( + private static boolean ffdhGroupSupportedByCipher( CipherSuite cipherSuite) { return cipherSuite.keyExAlgorithm == null || cipherSuite.keyExAlgorithm == KeyExAlgorithm.DHE_DSS diff --git a/test/jdk/sun/security/ssl/CipherSuite/RestrictNamedGroup.java b/test/jdk/sun/security/ssl/CipherSuite/RestrictNamedGroup.java index c4c343bf84ee..4ff0c6e6e159 100644 --- a/test/jdk/sun/security/ssl/CipherSuite/RestrictNamedGroup.java +++ b/test/jdk/sun/security/ssl/CipherSuite/RestrictNamedGroup.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 8226374 8242929 + * @bug 8226374 8242929 8314323 * @library /javax/net/ssl/templates * @summary Restrict signature algorithms and named groups * @run main/othervm RestrictNamedGroup x25519 @@ -36,6 +36,9 @@ * @run main/othervm RestrictNamedGroup ffdhe4096 * @run main/othervm RestrictNamedGroup ffdhe6144 * @run main/othervm RestrictNamedGroup ffdhe8192 + * @run main/othervm RestrictNamedGroup X25519MLKEM768 + * @run main/othervm RestrictNamedGroup SecP256r1MLKEM768 + * @run main/othervm RestrictNamedGroup SecP384r1MLKEM1024 */ import java.security.Security; diff --git a/test/jdk/sun/security/ssl/CipherSuite/SupportedGroups.java b/test/jdk/sun/security/ssl/CipherSuite/SupportedGroups.java index 88b0bf2489ae..8cf6ee2b5e62 100644 --- a/test/jdk/sun/security/ssl/CipherSuite/SupportedGroups.java +++ b/test/jdk/sun/security/ssl/CipherSuite/SupportedGroups.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,7 +23,7 @@ /* * @test - * @bug 8171279 + * @bug 8171279 8314323 * @library /javax/net/ssl/templates * @summary Test TLS connection with each individual supported group * @run main/othervm SupportedGroups x25519 @@ -36,6 +36,9 @@ * @run main/othervm SupportedGroups ffdhe4096 * @run main/othervm SupportedGroups ffdhe6144 * @run main/othervm SupportedGroups ffdhe8192 + * @run main/othervm SupportedGroups X25519MLKEM768 + * @run main/othervm SupportedGroups SecP256r1MLKEM768 + * @run main/othervm SupportedGroups SecP384r1MLKEM1024 */ import java.net.InetAddress; import java.util.Arrays; @@ -45,15 +48,24 @@ public class SupportedGroups extends SSLSocketTemplate { private static volatile int index; - private static final String[][][] protocols = { + private static final String[][][] protocolsForClassic = { {{"TLSv1.3"}, {"TLSv1.3"}}, {{"TLSv1.3", "TLSv1.2"}, {"TLSv1.2"}}, {{"TLSv1.2"}, {"TLSv1.3", "TLSv1.2"}}, {{"TLSv1.2"}, {"TLSv1.2"}} }; - public SupportedGroups() { + private static final String[][][] protocolsForHybrid = { + {{"TLSv1.3"}, {"TLSv1.3"}}, + {{"TLSv1.3", "TLSv1.2"}, {"TLSv1.3"}}, + {{"TLSv1.3"}, {"TLSv1.3", "TLSv1.2"}} + }; + + private final String[][][] protocols; + + public SupportedGroups(String[][][] protocols) { this.serverAddress = InetAddress.getLoopbackAddress(); + this.protocols = protocols; } // Servers are configured before clients, increment test case after. @@ -85,8 +97,18 @@ protected void configureServerSocket(SSLServerSocket serverSocket) { public static void main(String[] args) throws Exception { System.setProperty("jdk.tls.namedGroups", args[0]); + boolean hybridGroup = hybridNamedGroup(args[0]); + String[][][] protocols = hybridGroup ? + protocolsForHybrid : protocolsForClassic; + for (index = 0; index < protocols.length; index++) { - (new SupportedGroups()).run(); + (new SupportedGroups(protocols)).run(); } } + + private static boolean hybridNamedGroup(String namedGroup) { + return namedGroup.equals("X25519MLKEM768") || + namedGroup.equals("SecP256r1MLKEM768") || + namedGroup.equals("SecP384r1MLKEM1024"); + } } diff --git a/test/micro/org/openjdk/bench/java/security/SSLHandshake.java b/test/micro/org/openjdk/bench/java/security/SSLHandshake.java index 62c450455851..e6cf60fd1499 100644 --- a/test/micro/org/openjdk/bench/java/security/SSLHandshake.java +++ b/test/micro/org/openjdk/bench/java/security/SSLHandshake.java @@ -45,6 +45,7 @@ import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLEngineResult.HandshakeStatus; +import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManagerFactory; @@ -72,11 +73,22 @@ public class SSLHandshake { @Param({"true", "false"}) boolean resume; - @Param({"TLSv1.2", "TLS"}) - String tlsVersion; + @Param({ + "TLSv1.2-secp256r1", + "TLSv1.3-x25519", "TLSv1.3-secp256r1", "TLSv1.3-secp384r1", + "TLSv1.3-X25519MLKEM768", "TLSv1.3-SecP256r1MLKEM768", "TLSv1.3-SecP384r1MLKEM1024" + }) + String versionAndGroup; + + private String tlsVersion; + private String namedGroup; @Setup(Level.Trial) public void init() throws Exception { + String[] components = versionAndGroup.split("-", 2); + tlsVersion = components[0]; + namedGroup = components[1]; + KeyStore ks = TestCertificates.getKeyStore(); KeyStore ts = TestCertificates.getTrustStore(); @@ -181,5 +193,14 @@ private void createSSLEngines() { */ clientEngine = sslc.createSSLEngine("client", 80); clientEngine.setUseClientMode(true); + + // Set the key exchange named group in client and server engines + SSLParameters clientParams = clientEngine.getSSLParameters(); + clientParams.setNamedGroups(new String[]{namedGroup}); + clientEngine.setSSLParameters(clientParams); + + SSLParameters serverParams = serverEngine.getSSLParameters(); + serverParams.setNamedGroups(new String[]{namedGroup}); + serverEngine.setSSLParameters(serverParams); } } diff --git a/test/micro/org/openjdk/bench/javax/crypto/full/KEMBench.java b/test/micro/org/openjdk/bench/javax/crypto/full/KEMBench.java index 3386039c62ea..dc6d2060f5e4 100644 --- a/test/micro/org/openjdk/bench/javax/crypto/full/KEMBench.java +++ b/test/micro/org/openjdk/bench/javax/crypto/full/KEMBench.java @@ -23,34 +23,69 @@ package org.openjdk.bench.javax.crypto.full; import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.OperationsPerInvocation; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.infra.Blackhole; import javax.crypto.DecapsulateException; +import java.security.GeneralSecurityException; +import java.security.InvalidAlgorithmParameterException; import javax.crypto.KEM; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; +import java.security.Provider; +import java.security.Security; +import java.security.spec.ECGenParameterSpec; -public class KEMBench extends CryptoBase { +public abstract class KEMBench extends CryptoBase { public static final int SET_SIZE = 128; - @Param({"ML-KEM-512", "ML-KEM-768", "ML-KEM-1024" }) + @Param({}) private String algorithm; + @Param({""}) // Used when the KeyPairGenerator Alg != KEM Alg + private String kpgSpec; + private KeyPair[] keys; private byte[][] messages; private KEM kem; @Setup - public void setup() throws NoSuchAlgorithmException, InvalidKeyException { - kem = (prov == null) ? KEM.getInstance(algorithm) : KEM.getInstance(algorithm, prov); - KeyPairGenerator generator = (prov == null) ? KeyPairGenerator.getInstance(algorithm) : KeyPairGenerator.getInstance(algorithm, prov); + public void setup() throws NoSuchAlgorithmException, InvalidKeyException, + InvalidAlgorithmParameterException { + String kpgAlg; + String kpgParams; + kem = (prov == null) ? KEM.getInstance(algorithm) : + KEM.getInstance(algorithm, prov); + + // By default use the same provider for KEM and KPG + Provider kpgProv = prov; + if (kpgSpec.isEmpty()) { + kpgAlg = algorithm; + kpgParams = ""; + } else { + // The key pair generation spec is broken down from a colon- + // delimited string spec into 3 fields: + // [0] - the provider name + // [1] - the algorithm name + // [2] - the parameters (i.e. the name of the curve) + String[] kpgTok = kpgSpec.split(":"); + kpgProv = Security.getProvider(kpgTok[0]); + kpgAlg = kpgTok[1]; + kpgParams = kpgTok[2]; + } + KeyPairGenerator generator = (kpgProv == null) ? + KeyPairGenerator.getInstance(kpgAlg) : + KeyPairGenerator.getInstance(kpgAlg, kpgProv); + if (kpgParams != null && !kpgParams.isEmpty()) { + generator.initialize(new ECGenParameterSpec(kpgParams)); + } keys = new KeyPair[SET_SIZE]; for (int i = 0; i < keys.length; i++) { keys[i] = generator.generateKeyPair(); @@ -63,20 +98,79 @@ public void setup() throws NoSuchAlgorithmException, InvalidKeyException { } } + private static Provider getInternalJce() { + try { + Class dhClazz = Class.forName("sun.security.ssl.HybridProvider"); + return (Provider) dhClazz.getField("PROVIDER").get(null); + } catch (ReflectiveOperationException exc) { + throw new RuntimeException(exc); + } + } + @Benchmark @OperationsPerInvocation(SET_SIZE) public void encapsulate(Blackhole bh) throws InvalidKeyException { for (KeyPair kp : keys) { - bh.consume(kem.newEncapsulator(kp.getPublic()).encapsulate().encapsulation()); + bh.consume(kem.newEncapsulator(kp.getPublic()).encapsulate(). + encapsulation()); } } @Benchmark @OperationsPerInvocation(SET_SIZE) - public void decapsulate(Blackhole bh) throws InvalidKeyException, DecapsulateException { + public void decapsulate(Blackhole bh) throws InvalidKeyException, + DecapsulateException { for (int i = 0; i < messages.length; i++) { - bh.consume(kem.newDecapsulator(keys[i].getPrivate()).decapsulate(messages[i])); + bh.consume(kem.newDecapsulator(keys[i].getPrivate()). + decapsulate(messages[i])); } } + public static class MLKEM extends KEMBench { + @Param({"ML-KEM-512", "ML-KEM-768", "ML-KEM-1024" }) + private String algorithm; + + @Param({""}) // ML-KEM uses the same alg for KPG and KEM + private String kpgSpec; + } + + @Fork(value = 5, jvmArgs = {"-XX:+AlwaysPreTouch", "--add-opens", + "java.base/sun.security.ssl=ALL-UNNAMED"}) + public static class JSSE_DHasKEM extends KEMBench { + @Setup + public void init() { + try { + prov = getInternalJce(); + super.setup(); + } catch (GeneralSecurityException gse) { + throw new RuntimeException(gse); + } + } + + @Param({"DH"}) + private String algorithm; + + @Param({"SunEC:XDH:x25519", "SunEC:EC:secp256r1", "SunEC:EC:secp384r1"}) + private String kpgSpec; + } + + @Fork(value = 5, jvmArgs = {"-XX:+AlwaysPreTouch", "--add-opens", + "java.base/sun.security.ssl=ALL-UNNAMED"}) + public static class JSSE_Hybrid extends KEMBench { + @Setup + public void init() { + try { + prov = getInternalJce(); + super.setup(); + } catch (GeneralSecurityException gse) { + throw new RuntimeException(gse); + } + } + + @Param({"X25519MLKEM768", "SecP256r1MLKEM768", "SecP384r1MLKEM1024"}) + private String algorithm; + + @Param({""}) // ML-KEM uses the same alg for KPG and KEM + private String kpgSpec; + } } diff --git a/test/micro/org/openjdk/bench/javax/crypto/full/KeyPairGeneratorBench.java b/test/micro/org/openjdk/bench/javax/crypto/full/KeyPairGeneratorBench.java index 58daff28d880..5a3c72fb2638 100644 --- a/test/micro/org/openjdk/bench/javax/crypto/full/KeyPairGeneratorBench.java +++ b/test/micro/org/openjdk/bench/javax/crypto/full/KeyPairGeneratorBench.java @@ -22,13 +22,16 @@ */ package org.openjdk.bench.javax.crypto.full; +import org.openjdk.jmh.annotations.Fork; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Param; import org.openjdk.jmh.annotations.Setup; +import java.security.GeneralSecurityException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; +import java.security.Provider; public class KeyPairGeneratorBench extends CryptoBase { @@ -45,11 +48,21 @@ public void setup() throws NoSuchAlgorithmException { setupProvider(); generator = (prov == null) ? KeyPairGenerator.getInstance(algorithm) : KeyPairGenerator.getInstance(algorithm, prov); - if (keyLength > 0) { // not all key pair generators allow the use of key length + // not all key pair generators allow the use of key length + if (keyLength > 0) { generator.initialize(keyLength); } } + private static Provider getInternalJce() { + try { + Class dhClazz = Class.forName("sun.security.ssl.HybridProvider"); + return (Provider) dhClazz.getField("PROVIDER").get(null); + } catch (ReflectiveOperationException exc) { + throw new RuntimeException(exc); + } + } + @Benchmark public KeyPair generateKeyPair() { return generator.generateKeyPair(); @@ -118,4 +131,23 @@ public static class MLKEM extends KeyPairGeneratorBench { private int keyLength; } + @Fork(value = 5, jvmArgs = {"-XX:+AlwaysPreTouch", "--add-opens", + "java.base/sun.security.ssl=ALL-UNNAMED"}) + public static class JSSE_Hybrid extends KeyPairGeneratorBench { + @Setup + public void init() { + try { + prov = getInternalJce(); + super.setup(); + } catch (GeneralSecurityException gse) { + throw new RuntimeException(gse); + } + } + + @Param({"X25519MLKEM768", "SecP256r1MLKEM768", "SecP384r1MLKEM1024"}) + private String algorithm; + + @Param({"0"}) // Hybrid KPGs don't need key lengths + private int keyLength; + } } From ddbd925bc4b773717a38b0bdc70df2bc3055d6bb Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Sat, 14 Nov 2026 16:34:36 +0000 Subject: [PATCH 04/10] 8348286: [AIX] clang 17 introduces new warning Wtentative-Definitions which produces Build errors Reviewed-by: mbaesken Backport-of: a4942a2f7a2afdea5577eaae7cc4322ef1662fb9 --- .../native/libawt/awt/image/imageInitIDs.c | 74 ++++++++++- .../native/libawt/awt/image/imageInitIDs.h | 122 +++++++++--------- .../unix/native/libawt_xawt/awt/fp_pipewire.h | 90 ------------- .../libawt_xawt/awt/screencast_pipewire.c | 58 ++++++++- 4 files changed, 188 insertions(+), 156 deletions(-) delete mode 100644 src/java.desktop/unix/native/libawt_xawt/awt/fp_pipewire.h diff --git a/src/java.desktop/share/native/libawt/awt/image/imageInitIDs.c b/src/java.desktop/share/native/libawt/awt/image/imageInitIDs.c index 81bac6a414f1..75b585e3496c 100644 --- a/src/java.desktop/share/native/libawt/awt/image/imageInitIDs.c +++ b/src/java.desktop/share/native/libawt/awt/image/imageInitIDs.c @@ -24,8 +24,78 @@ */ #include #include "jni_util.h" -#define IMGEXTERN -#include "imageInitIDs.h" + +/* BufferedImage ids */ +jfieldID g_BImgRasterID; +jfieldID g_BImgTypeID; +jfieldID g_BImgCMID; +jmethodID g_BImgGetRGBMID; +jmethodID g_BImgSetRGBMID; + +/* Raster ids */ +jfieldID g_RasterWidthID; +jfieldID g_RasterHeightID; +jfieldID g_RasterMinXID; +jfieldID g_RasterMinYID; +jfieldID g_RasterBaseOriginXID; +jfieldID g_RasterBaseOriginYID; +jfieldID g_RasterSampleModelID; +jfieldID g_RasterDataBufferID; +jfieldID g_RasterNumDataElementsID; +jfieldID g_RasterNumBandsID; + +jfieldID g_BCRdataID; +jfieldID g_BCRscanstrID; +jfieldID g_BCRpixstrID; +jfieldID g_BCRdataOffsetsID; +jfieldID g_BCRtypeID; +jfieldID g_BPRdataID; +jfieldID g_BPRscanstrID; +jfieldID g_BPRpixstrID; +jfieldID g_BPRtypeID; +jfieldID g_BPRdataBitOffsetID; +jfieldID g_SCRdataID; +jfieldID g_SCRscanstrID; +jfieldID g_SCRpixstrID; +jfieldID g_SCRdataOffsetsID; +jfieldID g_SCRtypeID; +jfieldID g_ICRdataID; +jfieldID g_ICRscanstrID; +jfieldID g_ICRpixstrID; +jfieldID g_ICRdataOffsetsID; +jfieldID g_ICRtypeID; + +/* Color Model ids */ +jfieldID g_CMnBitsID; +jfieldID g_CMcspaceID; +jfieldID g_CMnumComponentsID; +jfieldID g_CMsuppAlphaID; +jfieldID g_CMisAlphaPreID; +jfieldID g_CMtransparencyID; +jfieldID g_CMcsTypeID; +jfieldID g_CMis_sRGBID; +jmethodID g_CMgetRGBdefaultMID; + +jfieldID g_ICMtransIdxID; +jfieldID g_ICMmapSizeID; +jfieldID g_ICMrgbID; + +/* Sample Model ids */ +jfieldID g_SMWidthID; +jfieldID g_SMHeightID; +jmethodID g_SMGetPixelsMID; +jmethodID g_SMSetPixelsMID; + +/* Single Pixel Packed Sample Model ids */ +jfieldID g_SPPSMmaskArrID; +jfieldID g_SPPSMmaskOffID; +jfieldID g_SPPSMnBitsID; +jfieldID g_SPPSMmaxBitID; + +/* Kernel ids */ +jfieldID g_KernelWidthID; +jfieldID g_KernelHeightID; +jfieldID g_KernelDataID; JNIEXPORT void JNICALL Java_java_awt_image_BufferedImage_initIDs(JNIEnv *env, jclass cls) { diff --git a/src/java.desktop/share/native/libawt/awt/image/imageInitIDs.h b/src/java.desktop/share/native/libawt/awt/image/imageInitIDs.h index 031d133edaeb..b015817188c1 100644 --- a/src/java.desktop/share/native/libawt/awt/image/imageInitIDs.h +++ b/src/java.desktop/share/native/libawt/awt/image/imageInitIDs.h @@ -28,82 +28,78 @@ #include "jni.h" -#ifndef IMGEXTERN -# define IMGEXTERN extern -#endif - /* BufferedImage ids */ -IMGEXTERN jfieldID g_BImgRasterID; -IMGEXTERN jfieldID g_BImgTypeID; -IMGEXTERN jfieldID g_BImgCMID; -IMGEXTERN jmethodID g_BImgGetRGBMID; -IMGEXTERN jmethodID g_BImgSetRGBMID; +extern jfieldID g_BImgRasterID; +extern jfieldID g_BImgTypeID; +extern jfieldID g_BImgCMID; +extern jmethodID g_BImgGetRGBMID; +extern jmethodID g_BImgSetRGBMID; /* Raster ids */ -IMGEXTERN jfieldID g_RasterWidthID; -IMGEXTERN jfieldID g_RasterHeightID; -IMGEXTERN jfieldID g_RasterBaseRasterID; -IMGEXTERN jfieldID g_RasterMinXID; -IMGEXTERN jfieldID g_RasterMinYID; -IMGEXTERN jfieldID g_RasterBaseOriginXID; -IMGEXTERN jfieldID g_RasterBaseOriginYID; -IMGEXTERN jfieldID g_RasterSampleModelID; -IMGEXTERN jfieldID g_RasterDataBufferID; -IMGEXTERN jfieldID g_RasterNumDataElementsID; -IMGEXTERN jfieldID g_RasterNumBandsID; +extern jfieldID g_RasterWidthID; +extern jfieldID g_RasterHeightID; +extern jfieldID g_RasterBaseRasterID; +extern jfieldID g_RasterMinXID; +extern jfieldID g_RasterMinYID; +extern jfieldID g_RasterBaseOriginXID; +extern jfieldID g_RasterBaseOriginYID; +extern jfieldID g_RasterSampleModelID; +extern jfieldID g_RasterDataBufferID; +extern jfieldID g_RasterNumDataElementsID; +extern jfieldID g_RasterNumBandsID; -IMGEXTERN jfieldID g_BCRdataID; -IMGEXTERN jfieldID g_BCRscanstrID; -IMGEXTERN jfieldID g_BCRpixstrID; -IMGEXTERN jfieldID g_BCRdataOffsetsID; -IMGEXTERN jfieldID g_BCRtypeID; -IMGEXTERN jfieldID g_BPRdataID; -IMGEXTERN jfieldID g_BPRscanstrID; -IMGEXTERN jfieldID g_BPRpixstrID; -IMGEXTERN jfieldID g_BPRtypeID; -IMGEXTERN jfieldID g_BPRdataBitOffsetID; -IMGEXTERN jfieldID g_SCRdataID; -IMGEXTERN jfieldID g_SCRscanstrID; -IMGEXTERN jfieldID g_SCRpixstrID; -IMGEXTERN jfieldID g_SCRdataOffsetsID; -IMGEXTERN jfieldID g_SCRtypeID; -IMGEXTERN jfieldID g_ICRdataID; -IMGEXTERN jfieldID g_ICRscanstrID; -IMGEXTERN jfieldID g_ICRpixstrID; -IMGEXTERN jfieldID g_ICRdataOffsetsID; -IMGEXTERN jfieldID g_ICRtypeID; +extern jfieldID g_BCRdataID; +extern jfieldID g_BCRscanstrID; +extern jfieldID g_BCRpixstrID; +extern jfieldID g_BCRdataOffsetsID; +extern jfieldID g_BCRtypeID; +extern jfieldID g_BPRdataID; +extern jfieldID g_BPRscanstrID; +extern jfieldID g_BPRpixstrID; +extern jfieldID g_BPRtypeID; +extern jfieldID g_BPRdataBitOffsetID; +extern jfieldID g_SCRdataID; +extern jfieldID g_SCRscanstrID; +extern jfieldID g_SCRpixstrID; +extern jfieldID g_SCRdataOffsetsID; +extern jfieldID g_SCRtypeID; +extern jfieldID g_ICRdataID; +extern jfieldID g_ICRscanstrID; +extern jfieldID g_ICRpixstrID; +extern jfieldID g_ICRdataOffsetsID; +extern jfieldID g_ICRtypeID; /* Color Model ids */ JNIEXPORT -IMGEXTERN jfieldID g_CMnBitsID; -IMGEXTERN jfieldID g_CMcspaceID; -IMGEXTERN jfieldID g_CMnumComponentsID; -IMGEXTERN jfieldID g_CMsuppAlphaID; -IMGEXTERN jfieldID g_CMisAlphaPreID; -IMGEXTERN jfieldID g_CMtransparencyID; -IMGEXTERN jfieldID g_CMcsTypeID; -IMGEXTERN jfieldID g_CMis_sRGBID; -IMGEXTERN jmethodID g_CMgetRGBdefaultMID; +extern jfieldID g_CMnBitsID; +extern jfieldID g_CMcspaceID; +extern jfieldID g_CMnumComponentsID; +extern jfieldID g_CMsuppAlphaID; +extern jfieldID g_CMisAlphaPreID; +extern jfieldID g_CMtransparencyID; +extern jfieldID g_CMcsTypeID; +extern jfieldID g_CMis_sRGBID; +extern jmethodID g_CMgetRGBdefaultMID; -IMGEXTERN jfieldID g_ICMtransIdxID; -IMGEXTERN jfieldID g_ICMmapSizeID; -IMGEXTERN jfieldID g_ICMrgbID; +extern jfieldID g_ICMtransIdxID; +extern jfieldID g_ICMmapSizeID; +extern jfieldID g_ICMrgbID; /* Sample Model ids */ -IMGEXTERN jfieldID g_SMWidthID; -IMGEXTERN jfieldID g_SMHeightID; -IMGEXTERN jmethodID g_SMGetPixelsMID; -IMGEXTERN jmethodID g_SMSetPixelsMID; +extern jfieldID g_SMWidthID; +extern jfieldID g_SMHeightID; +extern jmethodID g_SMGetPixelsMID; +extern jmethodID g_SMSetPixelsMID; /* Single Pixel Packed Sample Model ids */ -IMGEXTERN jfieldID g_SPPSMmaskArrID; -IMGEXTERN jfieldID g_SPPSMmaskOffID; -IMGEXTERN jfieldID g_SPPSMnBitsID; -IMGEXTERN jfieldID g_SPPSMmaxBitID; +extern jfieldID g_SPPSMmaskArrID; +extern jfieldID g_SPPSMmaskOffID; +extern jfieldID g_SPPSMnBitsID; +extern jfieldID g_SPPSMmaxBitID; /* Kernel ids */ -IMGEXTERN jfieldID g_KernelWidthID; -IMGEXTERN jfieldID g_KernelHeightID; -IMGEXTERN jfieldID g_KernelDataID; +extern jfieldID g_KernelWidthID; +extern jfieldID g_KernelHeightID; +extern jfieldID g_KernelDataID; #endif /* IMAGEINITIDS_H */ diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/fp_pipewire.h b/src/java.desktop/unix/native/libawt_xawt/awt/fp_pipewire.h deleted file mode 100644 index d39f7c833b77..000000000000 --- a/src/java.desktop/unix/native/libawt_xawt/awt/fp_pipewire.h +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Oracle designates this - * particular file as subject to the "Classpath" exception as provided - * by Oracle in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -#ifdef HEADLESS -#error This file should not be included in headless library -#endif -#ifndef _FP_PIPEWIRE_H -#define _FP_PIPEWIRE_H - - -struct pw_buffer *(*fp_pw_stream_dequeue_buffer)(struct pw_stream *stream); -const char * (*fp_pw_stream_state_as_string)(enum pw_stream_state state); -int (*fp_pw_stream_queue_buffer)(struct pw_stream *stream, - struct pw_buffer *buffer); -int (*fp_pw_stream_set_active)(struct pw_stream *stream, bool active); - -int (*fp_pw_stream_connect)( - struct pw_stream *stream, - enum pw_direction direction, - uint32_t target_id, - enum pw_stream_flags flags, - const struct spa_pod **params, - uint32_t n_params); - -struct pw_stream *(*fp_pw_stream_new)( - struct pw_core *core, - const char *name, - struct pw_properties *props -); -void (*fp_pw_stream_add_listener)(struct pw_stream *stream, - struct spa_hook *listener, - const struct pw_stream_events *events, - void *data); -int (*fp_pw_stream_disconnect)(struct pw_stream *stream); -void (*fp_pw_stream_destroy)(struct pw_stream *stream); - - -void (*fp_pw_init)(int *argc, char **argv[]); - -struct pw_core * -(*fp_pw_context_connect_fd)(struct pw_context *context, - int fd, - struct pw_properties *properties, - size_t user_data_size); - -int (*fp_pw_core_disconnect)(struct pw_core *core); - -struct pw_context * (*fp_pw_context_new)(struct pw_loop *main_loop, - struct pw_properties *props, - size_t user_data_size); - -struct pw_thread_loop * -(*fp_pw_thread_loop_new)(const char *name, const struct spa_dict *props); -struct pw_loop * (*fp_pw_thread_loop_get_loop)(struct pw_thread_loop *loop); -void (*fp_pw_thread_loop_signal)(struct pw_thread_loop *loop, - bool wait_for_accept); -void (*fp_pw_thread_loop_wait)(struct pw_thread_loop *loop); -void (*fp_pw_thread_loop_accept)(struct pw_thread_loop *loop); -int (*fp_pw_thread_loop_start)(struct pw_thread_loop *loop); -void (*fp_pw_thread_loop_stop)(struct pw_thread_loop *loop); -void (*fp_pw_thread_loop_destroy)(struct pw_thread_loop *loop); -void (*fp_pw_thread_loop_lock)(struct pw_thread_loop *loop); -void (*fp_pw_thread_loop_unlock)(struct pw_thread_loop *loop); - -struct pw_properties * (*fp_pw_properties_new)(const char *key, ...); - - -#endif //_FP_PIPEWIRE_H diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c b/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c index 62d12870ed2b..e40b69b9dd40 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c +++ b/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c @@ -33,7 +33,63 @@ #ifndef _AIX #include "screencast_pipewire.h" -#include "fp_pipewire.h" + +struct pw_buffer *(*fp_pw_stream_dequeue_buffer)(struct pw_stream *stream); +const char * (*fp_pw_stream_state_as_string)(enum pw_stream_state state); +int (*fp_pw_stream_queue_buffer)(struct pw_stream *stream, + struct pw_buffer *buffer); +int (*fp_pw_stream_set_active)(struct pw_stream *stream, bool active); + +int (*fp_pw_stream_connect)( + struct pw_stream *stream, + enum pw_direction direction, + uint32_t target_id, + enum pw_stream_flags flags, + const struct spa_pod **params, + uint32_t n_params); + +struct pw_stream *(*fp_pw_stream_new)( + struct pw_core *core, + const char *name, + struct pw_properties *props +); +void (*fp_pw_stream_add_listener)(struct pw_stream *stream, + struct spa_hook *listener, + const struct pw_stream_events *events, + void *data); +int (*fp_pw_stream_disconnect)(struct pw_stream *stream); +void (*fp_pw_stream_destroy)(struct pw_stream *stream); + + +void (*fp_pw_init)(int *argc, char **argv[]); + +struct pw_core * +(*fp_pw_context_connect_fd)(struct pw_context *context, + int fd, + struct pw_properties *properties, + size_t user_data_size); + +int (*fp_pw_core_disconnect)(struct pw_core *core); + +struct pw_context * (*fp_pw_context_new)(struct pw_loop *main_loop, + struct pw_properties *props, + size_t user_data_size); + +struct pw_thread_loop * +(*fp_pw_thread_loop_new)(const char *name, const struct spa_dict *props); +struct pw_loop * (*fp_pw_thread_loop_get_loop)(struct pw_thread_loop *loop); +void (*fp_pw_thread_loop_signal)(struct pw_thread_loop *loop, + bool wait_for_accept); +void (*fp_pw_thread_loop_wait)(struct pw_thread_loop *loop); +void (*fp_pw_thread_loop_accept)(struct pw_thread_loop *loop); +int (*fp_pw_thread_loop_start)(struct pw_thread_loop *loop); +void (*fp_pw_thread_loop_stop)(struct pw_thread_loop *loop); +void (*fp_pw_thread_loop_destroy)(struct pw_thread_loop *loop); +void (*fp_pw_thread_loop_lock)(struct pw_thread_loop *loop); +void (*fp_pw_thread_loop_unlock)(struct pw_thread_loop *loop); + +struct pw_properties * (*fp_pw_properties_new)(const char *key, ...); + #include "java_awt_event_KeyEvent.h" #include From 24cb6b8e7af16b7ba13a04049ceda3dc403ba07b Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Mon, 16 Nov 2026 14:23:12 +0000 Subject: [PATCH 05/10] 8392967: NTLMAuthSequence potential memory leak in getCredentialsHandle Backport-of: fb268a6f43fb7e7a0b962d10504a686acfd883ff --- src/java.base/windows/native/libnet/NTLMAuthSequence.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/java.base/windows/native/libnet/NTLMAuthSequence.c b/src/java.base/windows/native/libnet/NTLMAuthSequence.c index 3864ceedd51a..ab08ec94f864 100644 --- a/src/java.base/windows/native/libnet/NTLMAuthSequence.c +++ b/src/java.base/windows/native/libnet/NTLMAuthSequence.c @@ -73,7 +73,7 @@ JNIEXPORT jlong JNICALL Java_sun_net_www_protocol_http_ntlm_NTLMAuthSequence_get const CHAR *pUser = 0; const CHAR *pDomain = 0; const CHAR *pPassword = 0; - CredHandle *pCred; + CredHandle *pCred = NULL; TimeStamp ltime; jboolean isCopy; SECURITY_STATUS ss = SEC_E_INTERNAL_ERROR; @@ -144,6 +144,7 @@ JNIEXPORT jlong JNICALL Java_sun_net_www_protocol_http_ntlm_NTLMAuthSequence_get if (ss == SEC_E_OK) { return (jlong) pCred; } else { + free(pCred); return 0; } } From b308d52359556d0b65a057e62cbd222987c13929 Mon Sep 17 00:00:00 2001 From: Matthias Baesken Date: Mon, 16 Nov 2026 14:33:46 +0000 Subject: [PATCH 06/10] 8348872: jabswitch.cpp: regEnable and regDeleteValue leak reallocated data buffer Backport-of: 94a288ae652313b8d9c0e227faa62f1f07b83acb --- .../windows/native/jabswitch/jabswitch.cpp | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/src/jdk.accessibility/windows/native/jabswitch/jabswitch.cpp b/src/jdk.accessibility/windows/native/jabswitch/jabswitch.cpp index fdd7ff524da0..3e81fe11934f 100644 --- a/src/jdk.accessibility/windows/native/jabswitch/jabswitch.cpp +++ b/src/jdk.accessibility/windows/native/jabswitch/jabswitch.cpp @@ -299,12 +299,14 @@ void printVersion() { char* pVersionData = new char[nVersionSize]; if (!GetFileVersionInfo(executableFileName, 0, nVersionSize, pVersionData)) { printf("Unable to get version info.\n"); + delete[] pVersionData; return; } LPVOID pVersionInfo; UINT nSize; if (!VerQueryValue(pVersionData, _T("\\"), &pVersionInfo, &nSize)) { printf("Unable to query version value.\n"); + delete[] pVersionData; return; } VS_FIXEDFILEINFO *pVSInfo = (VS_FIXEDFILEINFO *)pVersionInfo; @@ -319,6 +321,7 @@ void printVersion() { "jabswitch enables or disables the Java Access Bridge.\n", versionString ); + delete[] pVersionData; } int regEnable() { @@ -342,9 +345,13 @@ int regEnable() { if (err == ERROR_SUCCESS) { err = _tcslwr_s(dataBuffer, DEFAULT_ALLOC); if (err) { + if (data != dataBuffer) delete[] data; + RegCloseKey(hKey); return -1; } if (_tcsstr(dataBuffer, STR_ACCESSBRIDGE) != NULL) { + if (data != dataBuffer) delete[] data; + RegCloseKey(hKey); return 0; // This is OK, e.g. ran enable twice and the value is there. } else { // add oracle_javaaccessbridge to Config key for HKCU @@ -353,9 +360,11 @@ int regEnable() { if (newStr != NULL) { wsprintf(newStr, L"%s,%s", dataBuffer, STR_ACCESSBRIDGE); RegSetValueEx(hKey, ACCESSIBILITY_CONFIG, 0, REG_SZ, (BYTE *)newStr, dataLength); + delete[] newStr; } } } + if (data != dataBuffer) delete[] data; RegCloseKey(hKey); } return err; @@ -387,9 +396,13 @@ int regDeleteValue(HKEY hFamilyKey, LPCWSTR lpSubKey) if (err == ERROR_SUCCESS) { err = _tcslwr_s(dataBuffer, DEFAULT_ALLOC); if (err) { + if (data != dataBuffer) delete[] data; + RegCloseKey(hKey); return -1; } if (_tcsstr(dataBuffer, STR_ACCESSBRIDGE) == NULL) { + if (data != dataBuffer) delete[] data; + RegCloseKey(hKey); return 0; // This is OK, e.g. ran disable twice and the value is not there. } else { // remove oracle_javaaccessbridge from Config key @@ -403,6 +416,9 @@ int regDeleteValue(HKEY hFamilyKey, LPCWSTR lpSubKey) _tcscpy_s(searchBuffer, DEFAULT_ALLOC, tok); err = _tcslwr_s(searchBuffer, DEFAULT_ALLOC); if (err) { + delete[] newStr; + if (data != dataBuffer) delete[] data; + RegCloseKey(hKey); return -1; } if (_tcsstr(searchBuffer, STR_ACCESSBRIDGE) == NULL) { @@ -416,8 +432,10 @@ int regDeleteValue(HKEY hFamilyKey, LPCWSTR lpSubKey) } dataLength = (_tcslen(newStr) + 1) * sizeof(TCHAR); RegSetValueEx(hKey, ACCESSIBILITY_CONFIG, 0, REG_SZ, (BYTE *)newStr, dataLength); + delete[] newStr; } } + if (data != dataBuffer) delete[] data; RegCloseKey(hKey); } return err; From 7506cd7c93b844b5ecbf15dcfca8c768776a64a2 Mon Sep 17 00:00:00 2001 From: Roland Mesde Date: Mon, 16 Nov 2026 16:57:58 +0000 Subject: [PATCH 07/10] 8375275: Error handling to raise illegal_parameter or internal_error alert in hybrid key exchange Reviewed-by: andrew Backport-of: cf424480f42ac220adee7034e0319cee0e9039db --- .../classes/sun/security/ssl/DHasKEM.java | 37 ++++++++++++- .../sun/security/ssl/KAKeyDerivation.java | 53 +++++++++++++++---- 2 files changed, 78 insertions(+), 12 deletions(-) diff --git a/src/java.base/share/classes/sun/security/ssl/DHasKEM.java b/src/java.base/share/classes/sun/security/ssl/DHasKEM.java index 763013f280c2..ef5c5b82f060 100644 --- a/src/java.base/share/classes/sun/security/ssl/DHasKEM.java +++ b/src/java.base/share/classes/sun/security/ssl/DHasKEM.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -101,7 +101,18 @@ public KEM.Encapsulated engineEncapsulate(int from, int to, return new KEM.Encapsulated( sub(dh, from, to), pkEm, null); + + } catch (IllegalArgumentException e) { + // ECDH validation failure + // all-zero shared secret + throw e; + } catch (InvalidKeyException e) { + // Invalid peer public key + // Convert InvalidKeyException to an unchecked exception + throw new IllegalArgumentException("Invalid peer public key", + e); } catch (Exception e) { + // Unexpected internal failure throw new ProviderException("internal error", e); } } @@ -126,6 +137,11 @@ public SecretKey engineDecapsulate(byte[] encapsulation, int from, PublicKey pkE = params.DeserializePublicKey(encapsulation); SecretKey dh = params.DH(algorithm, skR, pkE); return sub(dh, from, to); + + } catch (IllegalArgumentException e) { + // ECDH validation failure + // all-zero shared secret + throw e; } catch (IOException | InvalidKeyException e) { throw new DecapsulateException("Cannot decapsulate", e); } catch (Exception e) { @@ -248,7 +264,24 @@ private SecretKey DH(String alg, PrivateKey skE, PublicKey pkR) KeyAgreement ka = KeyAgreement.getInstance(kaAlgorithm); ka.init(skE); ka.doPhase(pkR, true); - return ka.generateSecret(alg); + SecretKey secret = ka.generateSecret(alg); + + // RFC 8446 section 7.4.2: checks for all-zero + // X25519/X448 shared secret. + if (kaAlgorithm.equals("X25519") || + kaAlgorithm.equals("X448")) { + byte[] s = secret.getEncoded(); + for (byte b : s) { + if (b != 0) { + return secret; + } + } + // Trigger ILLEGAL_PARAMETER alert + throw new IllegalArgumentException( + "All-zero shared secret"); + } + + return secret; } } } diff --git a/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java b/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java index 99d4c43f8dc3..29bb61f60973 100644 --- a/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java +++ b/src/java.base/share/classes/sun/security/ssl/KAKeyDerivation.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ import sun.security.util.RawKeySpec; +import javax.crypto.DecapsulateException; import javax.crypto.KEM; import javax.crypto.KeyAgreement; import javax.crypto.SecretKey; @@ -33,6 +34,7 @@ import javax.net.ssl.SSLHandshakeException; import java.io.IOException; import java.security.GeneralSecurityException; +import java.security.InvalidKeyException; import java.security.KeyFactory; import java.security.PrivateKey; import java.security.Provider; @@ -182,6 +184,9 @@ KEM.Encapsulated encapsulate(String algorithm, SecureRandom random) "encapsulation"); } + // All exceptions thrown during KEM encapsulation are mapped + // to TLS fatal alerts: + // illegal_parameter alert or internal_error alert. try { KeyFactory kf = (provider != null) ? KeyFactory.getInstance(algorithmName, provider) : @@ -198,8 +203,18 @@ KEM.Encapsulated encapsulate(String algorithm, SecureRandom random) SecretKey derived = deriveHandshakeSecret(algorithm, sharedSecret); return new KEM.Encapsulated(derived, enc.encapsulation(), null); - } catch (GeneralSecurityException gse) { - throw new SSLHandshakeException("Could not generate secret", gse); + } catch (IllegalArgumentException | InvalidKeyException e) { + // Peer validation failure + // ECDH all-zero shared secret (RFC 8446 section 7.4.2), + // ML-KEM encapsulation key check failure (FIPS-203 section 7.2) + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, e); + } catch (GeneralSecurityException e) { + // Cryptographic failure, + // deriveHandshakeSecret failure. + throw context.conContext.fatal(Alert.INTERNAL_ERROR, e); + } catch (RuntimeException e) { + // unexpected provider/runtime failure + throw context.conContext.fatal(Alert.INTERNAL_ERROR, e); } } @@ -215,13 +230,30 @@ private SecretKey t13DeriveKey(String type, // Using KEM: called by the client after receiving the KEM // ciphertext (keyshare) from the server in ServerHello. // The client decapsulates it using its private key. - KEM kem = (provider != null) - ? KEM.getInstance(algorithmName, provider) - : KEM.getInstance(algorithmName); - var decapsulator = kem.newDecapsulator(localPrivateKey); - sharedSecret = decapsulator.decapsulate( - keyshare, 0, decapsulator.secretSize(), - "TlsPremasterSecret"); + + // All exceptions thrown during KEM decapsulation are mapped + // to TLS fatal alerts: + // illegal_parameter alert or internal_error alert. + try { + KEM kem = (provider != null) + ? KEM.getInstance(algorithmName, provider) + : KEM.getInstance(algorithmName); + var decapsulator = kem.newDecapsulator(localPrivateKey); + sharedSecret = decapsulator.decapsulate( + keyshare, 0, decapsulator.secretSize(), + "TlsPremasterSecret"); + } catch (IllegalArgumentException | InvalidKeyException | + DecapsulateException e) { + // Peer validation failure + // ECDH all-zero shared secret (RFC 8446 section 7.4.2) + throw context.conContext.fatal(Alert.ILLEGAL_PARAMETER, e); + } catch (GeneralSecurityException e) { + // cryptographic failure + throw context.conContext.fatal(Alert.INTERNAL_ERROR, e); + } catch (RuntimeException e) { + // unexpected provider/runtime failure + throw context.conContext.fatal(Alert.INTERNAL_ERROR, e); + } } else { // Using traditional DH-style Key Agreement KeyAgreement ka = KeyAgreement.getInstance(algorithmName); @@ -232,6 +264,7 @@ private SecretKey t13DeriveKey(String type, return deriveHandshakeSecret(type, sharedSecret); } catch (GeneralSecurityException gse) { + // deriveHandshakeSecret() failure throw new SSLHandshakeException("Could not generate secret", gse); } } From 1a09d16e1353d5987604ded2506ee938048d7cda Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Mon, 16 Nov 2026 20:46:10 +0000 Subject: [PATCH 08/10] 8392993: Null pointer dereferences in screencast code Backport-of: 9a57f0efa7195ad8f0139650e60ceab05bb0b338 --- .../native/libawt_xawt/awt/gtk3_interface.c | 8 +- .../native/libawt_xawt/awt/gtk3_interface.h | 8 +- .../native/libawt_xawt/awt/gtk_interface.h | 7 +- .../libawt_xawt/awt/screencast_pipewire.c | 8 +- .../libawt_xawt/awt/screencast_portal.c | 137 +++++++++++++----- 5 files changed, 123 insertions(+), 45 deletions(-) diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c b/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c index cd943b02160a..ae3cb04bd7dc 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c +++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -583,6 +583,8 @@ GtkApi* gtk3_load(JNIEnv *env, const char* lib_name) fp_g_variant_get = dl_symbol("g_variant_get"); fp_g_variant_get_string = dl_symbol("g_variant_get_string"); fp_g_variant_get_uint32 = dl_symbol("g_variant_get_uint32"); + fp_g_variant_get_type_string = dl_symbol("g_variant_get_type_string"); + fp_g_variant_is_of_type = dl_symbol("g_variant_is_of_type"); fp_g_variant_iter_loop = dl_symbol("g_variant_iter_loop"); fp_g_variant_unref = dl_symbol("g_variant_unref"); fp_g_variant_lookup = dl_symbol("g_variant_lookup"); @@ -608,6 +610,7 @@ GtkApi* gtk3_load(JNIEnv *env, const char* lib_name) fp_g_error_free = dl_symbol("g_error_free"); fp_g_unix_fd_list_get = dl_symbol("g_unix_fd_list_get"); + fp_g_unix_fd_list_get_length = dl_symbol("g_unix_fd_list_get_length"); } /* Now we have only one kind of exceptions: NO_SYMBOL_EXCEPTION * Otherwise we can check the return value of setjmp method. @@ -3083,6 +3086,8 @@ static void gtk3_init(GtkApi* gtk) { gtk->g_variant_get = fp_g_variant_get; gtk->g_variant_get_string = fp_g_variant_get_string; gtk->g_variant_get_uint32 = fp_g_variant_get_uint32; + gtk->g_variant_get_type_string = fp_g_variant_get_type_string; + gtk->g_variant_is_of_type = fp_g_variant_is_of_type; gtk->g_variant_lookup = fp_g_variant_lookup; @@ -3111,6 +3116,7 @@ static void gtk3_init(GtkApi* gtk) { gtk->g_main_context_is_owner = fp_g_main_context_is_owner; gtk->g_error_free = fp_g_error_free; gtk->g_unix_fd_list_get = fp_g_unix_fd_list_get; + gtk->g_unix_fd_list_get_length = fp_g_unix_fd_list_get_length; gtk->gdk_pixbuf_new = fp_gdk_pixbuf_new; gtk->gdk_pixbuf_new_from_data = fp_gdk_pixbuf_new_from_data; diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.h b/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.h index d3a83677dd62..d58d106a3122 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.h +++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk3_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -750,6 +750,10 @@ static const gchar *(*fp_g_variant_get_string)(GVariant *value, static guint32 (*fp_g_variant_get_uint32)(GVariant *value); +static const gchar *(*fp_g_variant_get_type_string)(GVariant *value); + +static gboolean (*fp_g_variant_is_of_type)(GVariant *value, const GVariantType *type); + static gboolean (*fp_g_variant_lookup)(GVariant *dictionary, const gchar *key, const gchar *format_string, @@ -811,4 +815,6 @@ static gint (*fp_g_unix_fd_list_get)(GUnixFDList *list, gint index_, GError **error); +static gint (*fp_g_unix_fd_list_get_length)(GUnixFDList* list); + #endif /* !_GTK3_INTERFACE_H */ diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/gtk_interface.h b/src/java.desktop/unix/native/libawt_xawt/awt/gtk_interface.h index 11ec245ce8b0..876508893f64 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/gtk_interface.h +++ b/src/java.desktop/unix/native/libawt_xawt/awt/gtk_interface.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -685,6 +685,8 @@ typedef struct GtkApi { ...); const gchar *(*g_variant_get_string)(GVariant *value, gsize *length); guint32 (*g_variant_get_uint32)(GVariant *value); + const gchar *(*g_variant_get_type_string)(GVariant *value); + gboolean (*g_variant_is_of_type)(GVariant *value, const GVariantType *type); gboolean (*g_variant_lookup)(GVariant *dictionary, const gchar *key, @@ -804,6 +806,9 @@ typedef struct GtkApi { gint index_, GError **error); + gint (*g_unix_fd_list_get_length)(GUnixFDList* list); + + GdkPixbuf *(*gdk_pixbuf_new)(GdkColorspace colorspace, gboolean has_alpha, int bits_per_sample, diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c b/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c index e40b69b9dd40..c0724acad17a 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c +++ b/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -317,9 +317,11 @@ static void onStreamProcess(void *userdata) { spaBuffer = pwBuffer->buffer; if (!spaBuffer || spaBuffer->n_datas < 1 - || spaBuffer->datas[0].data == NULL) { + || spaBuffer->datas[0].data == NULL + || spaBuffer->datas[0].chunk == NULL) { DEBUG_SCREEN_PREFIX(screen, "!!! no data, n_datas %d\n", - spaBuffer->n_datas); + spaBuffer ? (int) spaBuffer->n_datas : -1); + fp_pw_stream_queue_buffer(data->stream, pwBuffer); return; } diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/screencast_portal.c b/src/java.desktop/unix/native/libawt_xawt/awt/screencast_portal.c index fad2cab16965..c513101a49fc 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/screencast_portal.c +++ b/src/java.desktop/unix/native/libawt_xawt/awt/screencast_portal.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2023, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,6 +41,27 @@ extern struct ScreenSpace screenSpace; struct XdgDesktopPortalApi *portal = NULL; extern int DEBUG_SCREENCAST_ENABLED; +static gboolean checkVariantType(const char *functionName, + int lineNum, + GVariant *value, + const char *expectedType, + const char *caption) { + if (value != NULL && gtk->g_variant_is_of_type( + value, (const GVariantType *) expectedType)) { + return TRUE; + } + + debug_screencast("%s:%i %s: invalid type %s, expected %s\n", + functionName, lineNum, caption, + value != NULL ? gtk->g_variant_get_type_string(value) : "NULL", + expectedType); + return FALSE; +} + +#define GET_VARIANT_CHECKED(VALUE, TYPE, FORMAT, CAPTION, ...) \ + (checkVariantType(__func__, __LINE__, (VALUE), (TYPE), (CAPTION)) && \ + (gtk->g_variant_get((VALUE), (FORMAT), __VA_ARGS__), TRUE)) + GDBusProxy *getProxy() { return isRemoteDesktop ? portal->remoteDesktopProxy : portal->screenCastProxy; } @@ -116,14 +137,20 @@ gboolean rebuildScreenData(GVariantIter *iterStreams, gboolean isTheOnlyMon) { DEBUG_SCREENCAST("\n==== screenId#%i\n", nodeID); if (screenIndex >= screenSpace.allocated) { - screenSpace.screens = realloc( + const int newAllocated = screenSpace.allocated + 1; + struct ScreenProps *newScreens = realloc( screenSpace.screens, - ++screenSpace.allocated * sizeof(struct ScreenProps) + newAllocated * sizeof(struct ScreenProps) ); - if (!screenSpace.screens) { + + if (!newScreens) { ERR("failed to allocate memory\n"); + gtk->g_variant_unref(prop); return FALSE; } + + screenSpace.screens = newScreens; + screenSpace.allocated = newAllocated; } struct ScreenProps * screen = &screenSpace.screens[screenIndex]; @@ -162,7 +189,6 @@ gboolean rebuildScreenData(GVariantIter *iterStreams, gboolean isTheOnlyMon) { DEBUG_SCREEN(screen); DEBUG_SCREENCAST("#---------------------#\n\n", NULL); - gtk->g_variant_unref(prop); screenIndex++; }; @@ -186,7 +212,7 @@ gboolean checkVersion() { : PORTAL_IFACE_SCREENCAST; if (version == 0) { - GError *error = NULL; + GError *err = NULL; GVariant *retVersion = gtk->g_dbus_proxy_call_sync( getProxy(), @@ -195,7 +221,7 @@ gboolean checkVersion() { interface, "version"), G_DBUS_CALL_FLAGS_NONE, - -1, NULL, NULL + -1, NULL, &err ); if (isRemoteDesktop) { @@ -206,13 +232,16 @@ gboolean checkVersion() { if (!retVersion) { //no backend on system DEBUG_SCREENCAST("!!! could not detect the %s version\n", interface); + ERR_HANDLE(err); return FALSE; } - ERR_HANDLE(error); - GVariant *varVersion = NULL; - gtk->g_variant_get(retVersion, "(v)", &varVersion); + if (!GET_VARIANT_CHECKED(retVersion, "(v)", "(v)", + "Version response", &varVersion)) { + gtk->g_variant_unref(retVersion); + return FALSE; + } if (!varVersion){ gtk->g_variant_unref(retVersion); @@ -220,11 +249,14 @@ gboolean checkVersion() { return FALSE; } - version = gtk->g_variant_get_uint32(varVersion); + if (!GET_VARIANT_CHECKED(varVersion, "u", "u", "Version", &version)) { + gtk->g_variant_unref(varVersion); + gtk->g_variant_unref(retVersion); + return FALSE; + } gtk->g_variant_unref(varVersion); gtk->g_variant_unref(retVersion); - } gboolean isVersionOk = isRemoteDesktop @@ -417,12 +449,12 @@ static void callbackScreenCastCreateSession( uint32_t status; GVariant *result = NULL; - gtk->g_variant_get( - parameters, - "(u@a{sv})", - &status, - &result - ); + if (!GET_VARIANT_CHECKED(parameters, "(ua{sv})", "(u@a{sv})", + "CreateSession response", &status, &result)) { + helper->isDone = TRUE; + callbackEnd(); + return; + } if (status != 0) { DEBUG_SCREENCAST("Failed to create ScreenCast: %u\n", status); @@ -431,6 +463,7 @@ static void callbackScreenCastCreateSession( DEBUG_SCREENCAST("session_handle returned %b %p\n", returned, helper->data) } + gtk->g_variant_unref(result); helper->isDone = TRUE; callbackEnd(); } @@ -541,7 +574,12 @@ static void callbackScreenCastSelectSources( uint32_t status; GVariant* result = NULL; - gtk->g_variant_get(parameters, "(u@a{sv})", &status, &result); + if (!GET_VARIANT_CHECKED(parameters, "(ua{sv})", "(u@a{sv})", + "SelectSources response", &status, &result)) { + helper->isDone = TRUE; + callbackEnd(); + return; + } if (status != 0) { DEBUG_SCREENCAST("Failed select sources: %u\n", status); @@ -574,7 +612,12 @@ static void callbackRemoteDesktopSelectDevices( uint32_t status; GVariant* result = NULL; - gtk->g_variant_get(parameters, "(u@a{sv})", &status, &result); + if (!GET_VARIANT_CHECKED(parameters, "(ua{sv})", "(u@a{sv})", + "SelectDevices response", &status, &result)) { + helper->isDone = TRUE; + callbackEnd(); + return; + } if (status != 0) { DEBUG_SCREENCAST("Failed select devices: %u\n", status); @@ -709,12 +752,19 @@ static void callbackScreenCastStart( GVariant* result = NULL; const gchar *oldToken = startHelper->token; - gtk->g_variant_get(parameters, "(u@a{sv})", &status, &result); + if (!GET_VARIANT_CHECKED(parameters, "(ua{sv})", "(u@a{sv})", + "Start response", &status, &result)) { + startHelper->result = RESULT_ERROR; + helper->isDone = TRUE; + callbackEnd(); + return; + } if (status != 0) { // Cancel pressed on the system dialog DEBUG_SCREENCAST("Failed to start screencast: %u\n", status); startHelper->result = RESULT_DENIED; + gtk->g_variant_unref(result); helper->isDone = TRUE; return; } @@ -722,14 +772,15 @@ static void callbackScreenCastStart( GVariant *streams = gtk->g_variant_lookup_value( result, "streams", - G_VARIANT_TYPE_ARRAY + (const GVariantType *) "a(ua{sv})" ); print_gvariant_content("Streams", streams); if (!streams) { - DEBUG_SCREENCAST("No streams available with current token\n", NULL); + DEBUG_SCREENCAST("No streams available with current token\n", NULL); startHelper->result = RESULT_NO_STREAMS; + gtk->g_variant_unref(result); helper->isDone = TRUE; return; } @@ -772,6 +823,7 @@ static void callbackScreenCastStart( helper->isDone = TRUE; gtk->g_variant_unref(streams); + gtk->g_variant_unref(result); callbackEnd(); } @@ -867,27 +919,36 @@ int portalScreenCastOpenPipewireRemote() { &err ); - if (err || !response) { - DEBUG_SCREENCAST("Failed to call OpenPipeWireRemote on session: %s\n", - err->message); + if (err || !response || !fdList) { + DEBUG_SCREENCAST("Failed to call OpenPipeWireRemote on session: %s, fdList %p\n", + err ? err->message : (!response ? "no response" : "no fd list"), + (void *)fdList); + if (response) { + gtk->g_variant_unref(response); + } + if (fdList) { + gtk->g_object_unref(fdList); + } ERR_HANDLE(err); return RESULT_ERROR; } gint32 index; - gtk->g_variant_get( - response, - "(h)", - &index, - &err - ); + if (!GET_VARIANT_CHECKED(response, "(h)", "(h)", + "OpenPipeWireRemote response", &index)) { + gtk->g_variant_unref(response); + gtk->g_object_unref(fdList); + return RESULT_ERROR; + } gtk->g_variant_unref(response); - if (err) { - DEBUG_SCREENCAST("Failed to get pipewire fd index: %s\n", - err->message); - ERR_HANDLE(err); + gint length = gtk->g_unix_fd_list_get_length(fdList); + + if (index < 0 || index >= length) { + DEBUG_SCREENCAST("Invalid pipewire fd index: %d (fdList length: %d)\n", + index, length); + gtk->g_object_unref(fdList); return RESULT_ERROR; } @@ -897,9 +958,7 @@ int portalScreenCastOpenPipewireRemote() { &err ); - if (fdList) { - gtk->g_object_unref(fdList); - } + gtk->g_object_unref(fdList); if (err) { DEBUG_SCREENCAST("Failed to get pipewire fd: %s\n", err->message); From 9a3054d70e779a1fa877ee70ea41bcaa761140bc Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Tue, 17 Nov 2026 18:31:34 +0000 Subject: [PATCH 09/10] 8346129: Simplify EdDSA & XDH curve name usage Reviewed-by: rschmelter Backport-of: e4e62789c7c89bd094480ca3fe19c123a34f9625 --- .../provider/certpath/AlgorithmChecker.java | 6 +- .../util/DisabledAlgorithmConstraints.java | 43 +++-- .../classes/sun/security/util/KeyUtil.java | 27 +++ .../DisabledAlgorithmPermits.java | 175 ++++++++++++++++++ 4 files changed, 229 insertions(+), 22 deletions(-) create mode 100644 test/jdk/sun/security/util/AlgorithmConstraints/DisabledAlgorithmPermits.java diff --git a/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java b/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java index 7ce31492b4b4..f127ac65cc7b 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,7 @@ import sun.security.util.Debug; import sun.security.util.DisabledAlgorithmConstraints; +import sun.security.util.KeyUtil; import sun.security.validator.Validator; import sun.security.x509.AlgorithmId; import sun.security.x509.X509CertImpl; @@ -206,7 +207,8 @@ public void check(Certificate cert, CertPathConstraintsParameters cp = new CertPathConstraintsParameters(trustedPubKey, variant, anchor, date); - dac.permits(trustedPubKey.getAlgorithm(), cp, true); + dac.permits(KeyUtil.getAlgorithm(trustedPubKey), + cp, true); } // Check the signature algorithm and parameters against constraints CertPathConstraintsParameters cp = diff --git a/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java b/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java index b657b61ecce2..54417092a7c0 100644 --- a/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java +++ b/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2024, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,18 +35,15 @@ import java.security.cert.CertPathValidatorException; import java.security.cert.CertPathValidatorException.BasicReason; import java.security.interfaces.ECKey; -import java.security.interfaces.XECKey; import java.security.spec.AlgorithmParameterSpec; import java.security.spec.InvalidParameterSpecException; import java.security.spec.MGF1ParameterSpec; -import java.security.spec.NamedParameterSpec; import java.security.spec.PSSParameterSpec; import java.time.DateTimeException; import java.time.Instant; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; @@ -262,7 +259,7 @@ public final void permits(String algorithm, ConstraintsParameters cp, if (checkKey) { // Check if named curves in the key are disabled. for (Key key : cp.getKeys()) { - for (String curve : getNamedCurveFromKey(key)) { + for (String curve : getNamedParametersFromKey(key)) { if (!cachedCheckAlgorithm(curve)) { throw new CertPathValidatorException( "Algorithm constraints check failed on disabled " + @@ -275,17 +272,23 @@ public final void permits(String algorithm, ConstraintsParameters cp, algorithmConstraints.permits(algorithm, cp, checkKey); } - private static List getNamedCurveFromKey(Key key) { - if (key instanceof ECKey) { - NamedCurve nc = CurveDB.lookup(((ECKey)key).getParams()); - return (nc == null ? List.of() - : Arrays.asList(nc.getNameAndAliases())); - } else if (key instanceof XECKey) { - return List.of( - ((NamedParameterSpec)((XECKey)key).getParams()).getName()); - } else { - return List.of(); - } + private static List getNamedParametersFromKey(Key key) { + return switch (key) { + case ECKey ecKey -> { + NamedCurve nc = CurveDB.lookup(ecKey.getParams()); + if (nc == null) { + yield List.of(); + } + yield List.of(nc.getNameAndAliases()); + } + default -> { + String n = KeyUtil.getAlgorithm(key); + if (n.equalsIgnoreCase(key.getAlgorithm())) { + yield List.of(n); + } + yield List.of(key.getAlgorithm(), n); + } + }; } // Check algorithm constraints with key and algorithm @@ -309,12 +312,12 @@ private boolean checkConstraints(Set primitives, } // check the key algorithm - if (!permits(primitives, key.getAlgorithm(), null)) { + if (!permits(primitives, KeyUtil.getAlgorithm(key), null)) { return false; } // If this is an elliptic curve, check if it is disabled - for (String curve : getNamedCurveFromKey(key)) { + for (String curve : getNamedParametersFromKey(key)) { if (!permits(primitives, curve, null)) { return false; } @@ -468,7 +471,7 @@ private List getConstraints(String algorithm) { // Check if KeySizeConstraints permit the specified key public boolean permits(Key key) { - List list = getConstraints(key.getAlgorithm()); + List list = getConstraints(KeyUtil.getAlgorithm(key)); if (list == null) { return true; } @@ -522,7 +525,7 @@ public void permits(String algorithm, ConstraintsParameters cp, if (checkKey) { for (Key key : cp.getKeys()) { - algorithms.add(key.getAlgorithm()); + algorithms.add(KeyUtil.getAlgorithm(key)); } } diff --git a/src/java.base/share/classes/sun/security/util/KeyUtil.java b/src/java.base/share/classes/sun/security/util/KeyUtil.java index 1db8d406bde1..702f8a20e322 100644 --- a/src/java.base/share/classes/sun/security/util/KeyUtil.java +++ b/src/java.base/share/classes/sun/security/util/KeyUtil.java @@ -184,6 +184,33 @@ public static final int getKeySize(AlgorithmParameters parameters) { return -1; } + /** + * If the key is a sub-algorithm of a larger group of algorithms, this + * method will return that sub-algorithm. For example, key.getAlgorithm() + * returns "EdDSA", but the underlying key may be "Ed448". For + * DisabledAlgorithmConstraints (DAC), this distinction is important. + * "EdDSA" means all curves for DAC, but when using it with + * KeyPairGenerator, "EdDSA" means "Ed25519". + */ + public static String getAlgorithm(Key key) { + /* + if (key instanceof PrivateKey ak && + ak.getParams() instanceof NamedParameterSpec nps) { + return nps.getName(); + } else if (key instanceof PublicKey ak && + ak.getParams() instanceof NamedParameterSpec nps) { + return nps.getName(); + } + */ + if (key instanceof PrivateKey || key instanceof PublicKey) { + AlgorithmParameterSpec params = KeyUtil.getParams(key); + if (params instanceof NamedParameterSpec nps) { + return nps.getName(); + } + } + return key.getAlgorithm(); + } + /** * Returns whether the key is valid or not. *

diff --git a/test/jdk/sun/security/util/AlgorithmConstraints/DisabledAlgorithmPermits.java b/test/jdk/sun/security/util/AlgorithmConstraints/DisabledAlgorithmPermits.java new file mode 100644 index 000000000000..913aa1266f46 --- /dev/null +++ b/test/jdk/sun/security/util/AlgorithmConstraints/DisabledAlgorithmPermits.java @@ -0,0 +1,175 @@ +/* + * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import sun.security.util.DisabledAlgorithmConstraints; + +import java.security.CryptoPrimitive; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; +import java.security.Security; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +/* + * @test + * @bug 8346129 + * @modules java.base/sun.security.util + * @summary Check DisabledAlgorithmConstraints using EdDSA & XDH against + * permit(Set, String, AP) and + * permit(Set, Key). Results will differ based + * on method used. The first method only can compare the String with the + * algorithms. The second can check the algorithm and NamedParameterSpec + * while results in more 'false' cases. + * + * @run main/othervm DisabledAlgorithmPermits Ed25519 + * @run main/othervm DisabledAlgorithmPermits Ed448 + * @run main/othervm DisabledAlgorithmPermits EdDSA + * @run main/othervm DisabledAlgorithmPermits X25519 + * @run main/othervm DisabledAlgorithmPermits X448 + * @run main/othervm DisabledAlgorithmPermits XDH + */ + +public class DisabledAlgorithmPermits { + public static void main(String[] args) throws Exception { + String algorithm = args[0]; + Security.setProperty("x", algorithm); + + // Expected table are the expected results from the test + List expected = switch (algorithm) { + case "Ed25519" -> + Arrays.asList( + new TestCase("EdDSA", true), + new TestCase("Ed25519", false), + new TestCase("Ed448", true), + new TestCase("X448", true), + new TestCase(1,"EdDSA", false), + new TestCase(1,"Ed25519", false), + new TestCase(1,"Ed448", true), + new TestCase(1,"X448", true)); + case "Ed448" -> + Arrays.asList( + new TestCase("EdDSA", true), + new TestCase("Ed25519", true), + new TestCase("Ed448", false), + new TestCase("X448", true), + new TestCase(1,"EdDSA", true), + new TestCase(1,"Ed25519", true), + new TestCase(1,"Ed448", false), + new TestCase(1,"X448", true)); + case "EdDSA" -> + Arrays.asList( + new TestCase("EdDSA", false), + new TestCase("Ed25519", true), + new TestCase("Ed448", true), + new TestCase("X448", true), + new TestCase(1,"EdDSA", false), + new TestCase(1,"Ed25519", false), + new TestCase(1,"Ed448", false), + new TestCase(1,"X448", true)); + case "X25519" -> + Arrays.asList( + new TestCase("XDH", true), + new TestCase("X25519", false), + new TestCase("X448", true), + new TestCase("Ed448", true), + new TestCase(1, "XDH", false), + new TestCase(1, "X25519", false), + new TestCase(1, "X448", true), + new TestCase(1, "Ed448", true)); + case "X448" -> + Arrays.asList( + new TestCase("XDH", true), + new TestCase("X25519", true), + new TestCase("X448", false), + new TestCase("Ed448", true), + new TestCase(1, "XDH", true), + new TestCase(1, "X25519", true), + new TestCase(1, "X448", false), + new TestCase(1, "Ed448", true)); + case "XDH" -> + Arrays.asList( + new TestCase("XDH", false), + new TestCase("X25519", true), + new TestCase("X448", true), + new TestCase("Ed448", true), + new TestCase(1, "XDH", false), + new TestCase(1, "X25519", false), + new TestCase(1, "X448", false), + new TestCase(1, "Ed448", true)); + default -> null; + }; + + Objects.requireNonNull(expected, "algorithm being tested " + + algorithm + " not in expected table"); + System.out.println("---"); + var dac = new DisabledAlgorithmConstraints("x"); + System.out.println("disabled algorithms = " + Security.getProperty("x")); + + // Using only testType 0, this tests that permit(Set<>, String, null) + // will check only the algorithm against the disabled list + expected.stream().filter(n->n.testType == 0).forEach(tc -> { + boolean r = dac.permits(Set.of(CryptoPrimitive.SIGNATURE), + tc.testAlgo, null); + System.out.print("\tpermits(Set.of(CryptoPrimitive.SIGNATURE), \"" + + tc.testAlgo + "\", null): " + r + " : " ); + if (r != tc.expected) { + System.out.println("failed."); + throw new AssertionError("failed. Expected " + + tc.expected); + } + System.out.println("pass"); + }); + + // Using only testType 1, this tests permit(Set<>, Key) that will look + // at both the key.getAlgorithm() and the key.getParams().getName() + // against the disabled list + expected.stream().filter(n->n.testType == 1).forEach(tc -> { + PrivateKey k; + try { + k = KeyPairGenerator.getInstance(tc.testAlgo).generateKeyPair(). + getPrivate(); + } catch (Exception e) { + throw new RuntimeException(e); + } + boolean r = dac.permits(Set.of(CryptoPrimitive.SIGNATURE), k); + System.out.print("\tpermits(Set.of(CryptoPrimitive.SIGNATURE), " + + tc.testAlgo + " privkey): " + r + " : " ); + if (r != tc.expected) { + System.out.println("failed."); + throw new AssertionError("failed. Expected " + + tc.expected); + } + System.out.println("pass"); + }); + System.out.println("---"); + } + + record TestCase(int testType, String testAlgo, boolean expected) { + TestCase(String testAlgo, boolean expected) { + this(0, testAlgo, expected); + } + } +} + From 31ccbe42fb0dcfbfbaf5d8248f7d17bdd2a90324 Mon Sep 17 00:00:00 2001 From: Goetz Lindenmaier Date: Tue, 17 Nov 2026 18:35:01 +0000 Subject: [PATCH 10/10] 8393416: [Ubuntu 26.10] screen capture test does not work with wayland Ubuntu 26.10 and hangs indefinitely Backport-of: 7606da1bbf4ad150f9887904ce9d3f5e3e6c0356 --- .../classes/sun/awt/X11GraphicsDevice.java | 10 +- .../sun/awt/screencast/ScreencastHelper.java | 20 +-- .../libawt_xawt/awt/screencast_pipewire.c | 147 ++++++++++++------ 3 files changed, 111 insertions(+), 66 deletions(-) diff --git a/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java b/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java index 0a1bc24599f8..f4fb2fcb8f47 100644 --- a/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java +++ b/src/java.desktop/unix/classes/sun/awt/X11GraphicsDevice.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -161,6 +161,14 @@ public Rectangle getBounds() { return bounds.getBounds(); } + /** + * Returns the screen bounds in native pixels, + * ignoring UI scaling and Xwayland display mode emulation. + */ + public Rectangle getNativeBounds() { + return pGetBounds(getScreen()); + } + public Insets getInsets() { return insets; } diff --git a/src/java.desktop/unix/classes/sun/awt/screencast/ScreencastHelper.java b/src/java.desktop/unix/classes/sun/awt/screencast/ScreencastHelper.java index 602788b66115..65cf01236492 100644 --- a/src/java.desktop/unix/classes/sun/awt/screencast/ScreencastHelper.java +++ b/src/java.desktop/unix/classes/sun/awt/screencast/ScreencastHelper.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2025, 2026, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,14 +26,12 @@ package sun.awt.screencast; import sun.awt.UNIXToolkit; -import sun.java2d.pipe.Region; +import sun.awt.X11GraphicsDevice; import sun.security.action.GetPropertyAction; -import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Rectangle; import java.awt.Toolkit; -import java.awt.geom.AffineTransform; import java.security.AccessController; import java.util.Arrays; import java.util.List; @@ -124,19 +122,7 @@ private static List getSystemScreensBounds() { .stream(GraphicsEnvironment .getLocalGraphicsEnvironment() .getScreenDevices()) - .map(graphicsDevice -> { - GraphicsConfiguration gc = - graphicsDevice.getDefaultConfiguration(); - Rectangle screen = gc.getBounds(); - AffineTransform tx = gc.getDefaultTransform(); - - return new Rectangle( - Region.clipRound(screen.x * tx.getScaleX()), - Region.clipRound(screen.y * tx.getScaleY()), - Region.clipRound(screen.width * tx.getScaleX()), - Region.clipRound(screen.height * tx.getScaleY()) - ); - }) + .map(d -> ((X11GraphicsDevice) d).getNativeBounds()) .toList(); } diff --git a/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c b/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c index c0724acad17a..253c646a77b9 100644 --- a/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c +++ b/src/java.desktop/unix/native/libawt_xawt/awt/screencast_pipewire.c @@ -28,6 +28,7 @@ #endif #include +#include #include "jni_util.h" #include "awt.h" @@ -74,14 +75,17 @@ int (*fp_pw_core_disconnect)(struct pw_core *core); struct pw_context * (*fp_pw_context_new)(struct pw_loop *main_loop, struct pw_properties *props, size_t user_data_size); +void (*fp_pw_context_destroy)(struct pw_context *context); struct pw_thread_loop * (*fp_pw_thread_loop_new)(const char *name, const struct spa_dict *props); struct pw_loop * (*fp_pw_thread_loop_get_loop)(struct pw_thread_loop *loop); void (*fp_pw_thread_loop_signal)(struct pw_thread_loop *loop, bool wait_for_accept); -void (*fp_pw_thread_loop_wait)(struct pw_thread_loop *loop); -void (*fp_pw_thread_loop_accept)(struct pw_thread_loop *loop); +int (*fp_pw_thread_loop_timed_wait_full)(struct pw_thread_loop *loop, + const struct timespec *abstime); +int (*fp_pw_thread_loop_get_time)(struct pw_thread_loop *loop, + struct timespec *abstime, int64_t timeout); int (*fp_pw_thread_loop_start)(struct pw_thread_loop *loop); void (*fp_pw_thread_loop_stop)(struct pw_thread_loop *loop); void (*fp_pw_thread_loop_destroy)(struct pw_thread_loop *loop); @@ -104,6 +108,9 @@ int DEBUG_SCREENCAST_ENABLED = FALSE; (*env)->ExceptionDescribe(env); \ } +// 10 s timeout for format negotiation and frames from all requested screens. +static const int64_t PIPEWIRE_TIMEOUT_NS = 10LL * 1000 * 1000 * 1000; + static gboolean hasPipewireFailed = FALSE; static gboolean sessionClosed = TRUE; static GString *activeSessionToken; @@ -159,6 +166,10 @@ static void doCleanup() { for (int i = 0; i < screenSpace.screenCount; ++i) { struct ScreenProps *screenProps = &screenSpace.screens[i]; + if (screenProps->captureDataPixbuf) { + gtk->g_object_unref(screenProps->captureDataPixbuf); + screenProps->captureDataPixbuf = NULL; + } if (screenProps->data) { if (screenProps->data->stream) { fp_pw_thread_loop_lock(pw.loop); @@ -184,6 +195,11 @@ static void doCleanup() { pw.core = NULL; } + if (pw.context) { + fp_pw_context_destroy(pw.context); + pw.context = NULL; + } + if (pw.loop) { fp_pw_thread_loop_destroy(pw.loop); pw.loop = NULL; @@ -282,7 +298,7 @@ static void onStreamParamChanged( data->rawFormat.size.height); data->hasFormat = TRUE; - fp_pw_thread_loop_signal(pw.loop, TRUE); + fp_pw_thread_loop_signal(pw.loop, FALSE); } static void onStreamProcess(void *userdata) { @@ -300,7 +316,6 @@ static void onStreamProcess(void *userdata) { if ( !data->hasFormat || !screen->shouldCapture - || screen->captureDataReady ) { return; } @@ -314,6 +329,11 @@ static void onStreamProcess(void *userdata) { return; } + if (screen->captureDataReady) { + fp_pw_stream_queue_buffer(data->stream, pwBuffer); + return; + } + spaBuffer = pwBuffer->buffer; if (!spaBuffer || spaBuffer->n_datas < 1 @@ -345,7 +365,6 @@ static void onStreamProcess(void *userdata) { ); GdkRectangle captureArea = screen->captureArea; - GdkRectangle screenBounds = screen->bounds; GdkPixbuf *pixbuf = gtk->gdk_pixbuf_new_from_data(spaData.data, GDK_COLORSPACE_RGB, @@ -356,9 +375,14 @@ static void onStreamProcess(void *userdata) { spaData.chunk->stride, NULL, NULL); + if (!pixbuf) { + ERR("Cannot create a pixbuf from stream data.\n"); + goto fail; + } - if (screen->bounds.width != streamWidth - || screen->bounds.height != streamHeight) { + gboolean needsScaling = screen->bounds.width != streamWidth + || screen->bounds.height != streamHeight; + if (needsScaling) { DEBUG_SCREEN_PREFIX(screen, "scaling stream data %dx%d -> %dx%d\n", streamWidth, streamHeight, @@ -370,37 +394,39 @@ static void onStreamProcess(void *userdata) { screen->bounds.height, GDK_INTERP_BILINEAR); + if (!scaled) { + ERR("Cannot scale the stream pixbuf.\n"); + goto fail; + } gtk->g_object_unref(pixbuf); pixbuf = scaled; } - GdkPixbuf *cropped = NULL; - if (captureArea.width != screenBounds.width - || captureArea.height != screenBounds.height) { - - cropped = gtk->gdk_pixbuf_new(GDK_COLORSPACE_RGB, + if (needsScaling + && captureArea.x == 0 && captureArea.y == 0 + && captureArea.width == screen->bounds.width + && captureArea.height == screen->bounds.height) { + screen->captureDataPixbuf = pixbuf; + } else { + GdkPixbuf *cropped = gtk->gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8, captureArea.width, captureArea.height); - if (cropped) { - gtk->gdk_pixbuf_copy_area(pixbuf, + if (!cropped) { + ERR("Cannot create a new pixbuf.\n"); + goto fail; + } + gtk->gdk_pixbuf_copy_area(pixbuf, captureArea.x, captureArea.y, captureArea.width, captureArea.height, cropped, 0, 0); - } else { - ERR("Cannot create a new pixbuf.\n"); - } gtk->g_object_unref(pixbuf); - pixbuf = NULL; - - data->screenProps->captureDataPixbuf = cropped; - } else { - data->screenProps->captureDataPixbuf = pixbuf; + screen->captureDataPixbuf = cropped; } screen->captureDataReady = TRUE; @@ -409,6 +435,15 @@ static void onStreamProcess(void *userdata) { fp_pw_stream_queue_buffer(data->stream, pwBuffer); fp_pw_thread_loop_signal(pw.loop, FALSE); + return; + + fail: + if (pixbuf) { + gtk->g_object_unref(pixbuf); + } + fp_pw_stream_queue_buffer(data->stream, pwBuffer); + hasPipewireFailed = TRUE; + fp_pw_thread_loop_signal(pw.loop, FALSE); } static void onStreamStateChanged( @@ -486,10 +521,13 @@ static bool startStream( } /** + * The caller must hold the PipeWire thread loop lock. + * * @param index of a screen + * @param captureDeadline shared deadline for format negotiation and screen capture * @return TRUE on success */ -static gboolean connectStream(int index) { +static gboolean connectStream(int index, const struct timespec *captureDeadline) { DEBUG_SCREENCAST("@@@ using screen %i\n", index); if (index >= screenSpace.screenCount) { DEBUG_SCREENCAST("!!! Wrong index for screen\n", NULL); @@ -501,9 +539,7 @@ static gboolean connectStream(int index) { data->screenProps = &screenSpace.screens[index]; if (!sessionClosed && data->stream) { - fp_pw_thread_loop_lock(pw.loop); int result = fp_pw_stream_set_active(data->stream, TRUE); - fp_pw_thread_loop_unlock(pw.loop); DEBUG_SCREEN_PREFIX(data->screenProps, "stream %p: activate result |%i|\n", @@ -528,7 +564,6 @@ static gboolean connectStream(int index) { if (!data->stream) { DEBUG_SCREEN_PREFIX(data->screenProps, "!!! Could not create a pipewire stream\n", NULL); - fp_pw_thread_loop_unlock(pw.loop); return FALSE; } @@ -544,18 +579,20 @@ static gboolean connectStream(int index) { if (!startStream(data->stream, screenSpace.screens[index].id)){ DEBUG_SCREEN_PREFIX(data->screenProps, "!!! Could not start a pipewire stream\n", NULL); - fp_pw_thread_loop_unlock(pw.loop); return FALSE; } - while (!data->hasFormat) { - fp_pw_thread_loop_wait(pw.loop); - fp_pw_thread_loop_accept(pw.loop); - if (hasPipewireFailed) { - fp_pw_thread_loop_unlock(pw.loop); + while (!hasPipewireFailed && !data->hasFormat) { + int result = fp_pw_thread_loop_timed_wait_full(pw.loop, captureDeadline); + if (result < 0) { + DEBUG_SCREEN_PREFIX(data->screenProps, + "Format wait failed: %d\n", result); return FALSE; } } + if (hasPipewireFailed) { + return FALSE; + } DEBUG_SCREEN_PREFIX(data->screenProps, "frame size: %dx%d\n", @@ -637,7 +674,7 @@ static const struct pw_core_events coreEvents = { * @param requestedArea requested screenshot area * @return TRUE on success */ -static gboolean doLoop(GdkRectangle requestedArea) { +static gboolean doLoop(GdkRectangle requestedArea, struct timespec *captureDeadline) { gboolean isLoopLockTaken = FALSE; if (!pw.loop && !sessionClosed) { pw.loop = fp_pw_thread_loop_new("AWT Pipewire Thread", NULL); @@ -689,6 +726,13 @@ static gboolean doLoop(GdkRectangle requestedArea) { } pw_core_add_listener(pw.core, &pw.coreListener, &coreEvents, NULL); + } else if (pw.loop) { + fp_pw_thread_loop_lock(pw.loop); + isLoopLockTaken = TRUE; + } + + if (fp_pw_thread_loop_get_time(pw.loop, captureDeadline, PIPEWIRE_TIMEOUT_NS) < 0) { + goto fail; } for (int i = 0; i < screenSpace.screenCount; ++i) { @@ -708,7 +752,7 @@ static gboolean doLoop(GdkRectangle requestedArea) { DEBUG_SCREEN_PREFIX(screen, "@@@ adding screen %i\n", i); if (checkScreen(i, requestedArea)) { - if (!connectStream(i)){ + if (!connectStream(i, captureDeadline)){ goto fail; } } @@ -783,11 +827,12 @@ static gboolean loadSymbols() { LOAD_SYMBOL(fp_pw_context_connect_fd, "pw_context_connect_fd"); LOAD_SYMBOL(fp_pw_core_disconnect, "pw_core_disconnect"); LOAD_SYMBOL(fp_pw_context_new, "pw_context_new"); + LOAD_SYMBOL(fp_pw_context_destroy, "pw_context_destroy"); LOAD_SYMBOL(fp_pw_thread_loop_new, "pw_thread_loop_new"); LOAD_SYMBOL(fp_pw_thread_loop_get_loop, "pw_thread_loop_get_loop"); LOAD_SYMBOL(fp_pw_thread_loop_signal, "pw_thread_loop_signal"); - LOAD_SYMBOL(fp_pw_thread_loop_wait, "pw_thread_loop_wait"); - LOAD_SYMBOL(fp_pw_thread_loop_accept, "pw_thread_loop_accept"); + LOAD_SYMBOL(fp_pw_thread_loop_timed_wait_full, "pw_thread_loop_timed_wait_full"); + LOAD_SYMBOL(fp_pw_thread_loop_get_time, "pw_thread_loop_get_time"); LOAD_SYMBOL(fp_pw_thread_loop_start, "pw_thread_loop_start"); LOAD_SYMBOL(fp_pw_thread_loop_stop, "pw_thread_loop_stop"); LOAD_SYMBOL(fp_pw_thread_loop_destroy, "pw_thread_loop_destroy"); @@ -954,19 +999,27 @@ static int makeScreencast( return pw.pwFd; } - if (!doLoop(*requestedArea)) { + struct timespec captureDeadline; + if (!doLoop(*requestedArea, &captureDeadline)) { return RESULT_ERROR; } - while (!isAllDataReady()) { - fp_pw_thread_loop_lock(pw.loop); - fp_pw_thread_loop_wait(pw.loop); - fp_pw_thread_loop_unlock(pw.loop); - if (hasPipewireFailed) { - doCleanup(); - return RESULT_ERROR; + fp_pw_thread_loop_lock(pw.loop); + int waitResult = 0; + while (!hasPipewireFailed && !isAllDataReady()) { + waitResult = fp_pw_thread_loop_timed_wait_full(pw.loop, &captureDeadline); + if (waitResult < 0) { + DEBUG_SCREENCAST("Frame wait failed: %d\n", waitResult); + break; } } + gboolean failed = hasPipewireFailed || waitResult < 0; + fp_pw_thread_loop_unlock(pw.loop); + + if (failed) { + doCleanup(); + return RESULT_ERROR; + } return RESULT_OK; } @@ -1097,17 +1150,15 @@ JNIEXPORT jint JNICALL Java_sun_awt_screencast_ScreencastHelper_getRGBPixelsImpl } } + fp_pw_thread_loop_lock(pw.loop); if (screenProps->captureDataPixbuf) { gtk->g_object_unref(screenProps->captureDataPixbuf); screenProps->captureDataPixbuf = NULL; } screenProps->shouldCapture = FALSE; - - fp_pw_thread_loop_lock(pw.loop); fp_pw_stream_set_active(screenProps->data->stream, FALSE); - fp_pw_thread_loop_unlock(pw.loop); - screenProps->captureDataReady = FALSE; + fp_pw_thread_loop_unlock(pw.loop); } }