From 4b67c355b409a8015d50002ac43c2e252acabc8d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=A1clav=20Muzik=C3=A1=C5=99?= Date: Fri, 4 Dec 2026 21:42:28 +0100 Subject: [PATCH] Support for Hybrid Key Exchange MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Closes #43691 Closes #50674 Closes #50789 Closes #50676 Signed-off-by: Václav Muzikář --- .../java/org/keycloak/common/Profile.java | 2 + .../release_notes/topics/27_0_0.adoc | 10 + docs/guides/server/enabletls.adoc | 3 + docs/guides/server/fips.adoc | 2 + docs/guides/server/pinned-guides | 1 + .../server/post-quantum-cryptography.adoc | 93 +++++ .../quarkus/deployment/KeycloakProcessor.java | 9 + .../quarkus/runtime/KeycloakRecorder.java | 9 + .../mappers/HttpPropertyMappers.java | 22 + .../mappers/ManagementPropertyMappers.java | 22 + .../runtime/tls/HybridKeyExchange.java | 152 +++++++ .../configuration/ConfigurationTest.java | 25 ++ .../ManagementConfigurationTest.java | 24 ++ .../runtime/tls/HybridKeyExchangeTest.java | 62 +++ .../keycloak/it/cli/dist/FakeTlsServer.java | 375 ++++++++++++++++++ .../dist/TlsHybridKeyExchangeDistTest.java | 136 +++++++ .../TlsHybridKeyExchangeOutgoingDistTest.java | 203 ++++++++++ 17 files changed, 1150 insertions(+) create mode 100644 docs/guides/server/post-quantum-cryptography.adoc create mode 100644 quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/tls/HybridKeyExchange.java create mode 100644 quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/tls/HybridKeyExchangeTest.java create mode 100644 quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/FakeTlsServer.java create mode 100644 quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/TlsHybridKeyExchangeDistTest.java create mode 100644 quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/TlsHybridKeyExchangeOutgoingDistTest.java diff --git a/common/src/main/java/org/keycloak/common/Profile.java b/common/src/main/java/org/keycloak/common/Profile.java index 708be569f6f..3b3971060eb 100755 --- a/common/src/main/java/org/keycloak/common/Profile.java +++ b/common/src/main/java/org/keycloak/common/Profile.java @@ -203,6 +203,8 @@ public enum Feature { RESOURCE_INDICATORS("Resource Indicators for OAuth 2.0", Type.EXPERIMENTAL), + TLS_HYBRID_KEY_EXCHANGE("Post-quantum hybrid key exchange for TLS connections", Type.EXPERIMENTAL), + IDENTITY_BROKERING_API_V1("Identity Brokering API V1", Type.DEFAULT, 1, true, null, null), IDENTITY_BROKERING_API_V2("Identity Brokering API V2", Type.DISABLED_BY_DEFAULT, 2); diff --git a/docs/documentation/release_notes/topics/27_0_0.adoc b/docs/documentation/release_notes/topics/27_0_0.adoc index 48ecfa8075a..26218cc6b0c 100644 --- a/docs/documentation/release_notes/topics/27_0_0.adoc +++ b/docs/documentation/release_notes/topics/27_0_0.adoc @@ -24,6 +24,16 @@ The default signature algorithms remain unchanged. For requirements, see link:{adminguide_link}#_webauthn-pqc[Post-quantum signature algorithms] in the {adminguide_name}. +== Post-quantum hybrid key exchange for TLS (experimental) + +{project_name} introduces experimental support for preferring post-quantum hybrid key exchange groups, such as `X25519MLKEM768`, in TLS connections. +Enable it with `--features=tls-hybrid-key-exchange`. +It applies to the HTTPS listener, the management interface, and all outgoing TLS connections, for example to identity providers, databases, LDAP, and SMTP servers. +Classical key exchange stays available for peers that do not support hybrid groups. +A Java runtime supporting hybrid key exchange is required, for example OpenJDK 25.0.5 or later. + +For more details, see the https://www.keycloak.org/server/post-quantum-cryptography[Using post-quantum cryptography] guide. + == PAR discovery respects the feature flag When the `par` feature is disabled, OpenID Connect discovery no longer advertises the pushed authorization request endpoint, including its mTLS alias, or `require_pushed_authorization_requests`. diff --git a/docs/guides/server/enabletls.adoc b/docs/guides/server/enabletls.adoc index f2697c13265..7bd4e40066e 100644 --- a/docs/guides/server/enabletls.adoc +++ b/docs/guides/server/enabletls.adoc @@ -73,6 +73,9 @@ However, as a temporary work-around, you can enable deprecated protocols by runn For example to only enable TLSv1.3, use a command such as the following: `kc.sh start --https-protocols=TLSv1.3`. +== Post-quantum hybrid key exchange +To prefer post-quantum hybrid key exchange groups in TLS connections, see <@links.server id="post-quantum-cryptography"/>. + == Switching the HTTPS port {project_name} listens for HTTPS traffic on port `8443`. To change this port, use the following command: <@kc.start parameters="--https-port="/> diff --git a/docs/guides/server/fips.adoc b/docs/guides/server/fips.adoc index 664cc79a034..bd3ed47072b 100644 --- a/docs/guides/server/fips.adoc +++ b/docs/guides/server/fips.adoc @@ -162,6 +162,8 @@ always fulfils this requirement. == Other restrictions +The experimental `tls-hybrid-key-exchange` feature is not supported in FIPS mode. For more details, see <@links.server id="post-quantum-cryptography"/>. + To have SAML working, make sure that a `XMLDSig` security provider is available in your security providers. To have Kerberos working, make sure that a `SunJGSS` security provider is available. In FIPS enabled RHEL 9 in OpenJDK 21, the `XMLDSig` security provider may be already enabled in the `java.security` by default and the same applies with latest OpenJDK 17. But with older OpenJDK 17, it may not be enabled by default, which means that SAML effectively cannot work. diff --git a/docs/guides/server/pinned-guides b/docs/guides/server/pinned-guides index 2059fad1a78..daf5e946584 100644 --- a/docs/guides/server/pinned-guides +++ b/docs/guides/server/pinned-guides @@ -16,6 +16,7 @@ caching outgoinghttp keycloak-truststore mutual-tls +post-quantum-cryptography features configuration-provider logging diff --git a/docs/guides/server/post-quantum-cryptography.adoc b/docs/guides/server/post-quantum-cryptography.adoc new file mode 100644 index 00000000000..b595033e35b --- /dev/null +++ b/docs/guides/server/post-quantum-cryptography.adoc @@ -0,0 +1,93 @@ +<#import "/templates/guide.adoc" as tmpl> +<#import "/templates/kc.adoc" as kc> +<#import "/templates/links.adoc" as links> + +<@tmpl.guide +title="Using post-quantum cryptography" +summary="Protect {project_name} with cryptography designed to resist attacks by quantum computers."> + +Post-quantum cryptography (PQC) uses algorithms designed to stay secure even against an attacker with a large quantum computer. +This {section} describes the post-quantum capabilities of {project_name} and how to enable them. + +All capabilities described here are experimental and disabled by default. + +.Post-quantum capabilities +[%autowidth] +|=== +|Capability |Feature |Protects + +|<> +|`tls-hybrid-key-exchange` +|Confidentiality of the data sent over incoming and outgoing TLS connections + +|<> +|`webauthn-ml-dsa` +|Authenticity of WebAuthn credentials +|=== + +[[tls-hybrid-key-exchange]] +== Hybrid key exchange for TLS (Experimental) + +Hybrid key exchange combines a classical key exchange with a post-quantum one, so the TLS session stays protected even if one of them is broken. +It protects against recording encrypted traffic today and decrypting it later with a quantum computer. + +To enable it: + +<@kc.start parameters="--features=tls-hybrid-key-exchange"/> + +When enabled, {project_name} prefers the hybrid TLS 1.3 key exchange groups over the classical ones. +The following groups are enabled, in the order of preference: + +[%autowidth] +|=== +|Kind |Groups + +|Hybrid +|`X25519MLKEM768`, `SecP256r1MLKEM768`, `SecP384r1MLKEM1024` + +|Classical +|`x25519`, `secp256r1`, `x448`, `secp384r1`, `secp521r1` +|=== + +The classical groups stay enabled, so a peer that does not support hybrid key exchange can still connect. +Other groups the Java runtime enables by default, such as the finite field groups `ffdhe2048` or `ffdhe3072`, are not enabled. + +=== Incoming connections + +The groups apply to the HTTPS listener and the management interface. +For details on configuring them, see <@links.server id="enabletls"/> and <@links.server id="management-interface"/>. + +The group used for a connection is selected from the groups the client sends a key share for. +A client that supports hybrid key exchange but prefers a classical group therefore still negotiates the classical group. + +=== Outgoing connections + +The groups apply to all outgoing TLS connections of {project_name}, for example: + +* HTTP requests, such as requests to identity providers. See <@links.server id="outgoinghttp"/>. +* Databases. See <@links.server id="db"/>. +* LDAP and SMTP servers. +* External {jdgserver_name} and the communication between the nodes of a cluster. See <@links.server id="caching"/>. + +To apply the groups, {project_name} sets the `jdk.tls.namedGroups` Java system property. + +=== Requirements and limitations + +* A Java runtime supporting hybrid key exchange is required, for example OpenJDK 25.0.5 or later. +{project_name} fails to start when the feature is enabled and no hybrid group is available. +* The feature is not supported in FIPS mode. {project_name} fails to start when both are enabled. For more details on FIPS mode, see <@links.server id="fips"/>. +* When the feature is disabled, {project_name} does not change the key exchange groups. +Hybrid key exchange can still be used if the Java runtime enables it by default. + +[[webauthn-signatures]] +== WebAuthn signature algorithms (Experimental) + +WebAuthn policies support the post-quantum signature algorithms `ML-DSA-44`, `ML-DSA-65`, and `ML-DSA-87`. + +To enable them: + +<@kc.start parameters="--features=webauthn-ml-dsa"/> + +For the requirements and configuration, see link:{adminguide_link}#_webauthn-pqc[Post-quantum signature algorithms] in the {adminguide_name}. + + diff --git a/quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/KeycloakProcessor.java b/quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/KeycloakProcessor.java index d4e9be3a4e8..f147d5078cf 100644 --- a/quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/KeycloakProcessor.java +++ b/quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/KeycloakProcessor.java @@ -103,6 +103,7 @@ import org.keycloak.quarkus.runtime.services.health.KeycloakReadyHealthCheck; import org.keycloak.quarkus.runtime.storage.database.jpa.NamedJpaConnectionProviderFactory; import org.keycloak.quarkus.runtime.themes.FlatClasspathThemeResourceProviderFactory; +import org.keycloak.quarkus.runtime.tls.HybridKeyExchange; import org.keycloak.representations.provider.ScriptProviderDescriptor; import org.keycloak.representations.provider.ScriptProviderMetadata; import org.keycloak.services.DefaultKeycloakSessionFactory; @@ -1045,8 +1046,16 @@ public List scan(MethodInfo method, ClassInfo actualEndp @Record(ExecutionTime.STATIC_INIT) void initCrypto(KeycloakRecorder recorder) { FipsMode fipsMode = getFipsMode(); + boolean hybridKeyExchange = HybridKeyExchange.isEnabled(); + if (hybridKeyExchange) { + // needs to be done before anything initializes JSSE + recorder.configureTlsHybridKeyExchange(); + } recorder.setCryptoProvider(fipsMode); recorder.configureTruststore(fipsMode); + if (hybridKeyExchange) { + recorder.verifyTlsHybridKeyExchange(); + } } private FipsMode getFipsMode() { diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/KeycloakRecorder.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/KeycloakRecorder.java index ba656371f9e..4f6af074874 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/KeycloakRecorder.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/KeycloakRecorder.java @@ -64,6 +64,7 @@ import org.keycloak.quarkus.runtime.services.MisdirectedFilter; import org.keycloak.quarkus.runtime.services.RejectNonNormalizedPathFilter; import org.keycloak.quarkus.runtime.storage.database.liquibase.FastServiceLocator; +import org.keycloak.quarkus.runtime.tls.HybridKeyExchange; import org.keycloak.representations.userprofile.config.UPConfig; import org.keycloak.theme.ClasspathThemeProviderFactory; import org.keycloak.truststore.TruststoreBuilder; @@ -337,6 +338,14 @@ public void setCryptoProvider(FipsMode fipsMode) { } } + public void configureTlsHybridKeyExchange() { + HybridKeyExchange.configure(); + } + + public void verifyTlsHybridKeyExchange() { + HybridKeyExchange.verify(); + } + public void configureProtoStreamSchemas(List schemas) { Marshalling.setSchemas(schemas); } diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/HttpPropertyMappers.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/HttpPropertyMappers.java index 607351b6d1c..0c1e69fa566 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/HttpPropertyMappers.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/HttpPropertyMappers.java @@ -23,6 +23,7 @@ import org.keycloak.quarkus.runtime.cli.PropertyException; import org.keycloak.quarkus.runtime.cli.command.AbstractCommand; import org.keycloak.quarkus.runtime.configuration.Configuration; +import org.keycloak.quarkus.runtime.tls.HybridKeyExchange; import io.quarkus.runtime.LaunchMode; import io.quarkus.runtime.configuration.DurationConverter; @@ -45,6 +46,16 @@ public final class HttpPropertyMappers implements PropertyMapperGrouping { .synthetic() .build(); + private static final Option SYNTHETIC_TLS_PQC_ENFORCEMENT_POLICY = new OptionBuilder<>("https-tls-pqc-enforcement-policy-hidden", String.class) + .buildTime(false) + .synthetic() + .build(); + + private static final Option SYNTHETIC_TLS_KEY_EXCHANGE_GROUPS = new OptionBuilder<>("https-tls-key-exchange-groups-hidden", String.class) + .buildTime(false) + .synthetic() + .build(); + enum StoreType { PKCS12, JKS, PEM, OTHER } @@ -113,6 +124,17 @@ public List> getPropertyMappers() { .build() ); + mappers.addAll(List.of( + fromOption(SYNTHETIC_TLS_PQC_ENFORCEMENT_POLICY) + .to(TLS_PREFIX + "pqc-enforcement-policy") + .transformer((v, c) -> HybridKeyExchange.isEnabled() ? HybridKeyExchange.PQC_ENFORCEMENT_POLICY : null) + .build(), + fromOption(SYNTHETIC_TLS_KEY_EXCHANGE_GROUPS) + .to(TLS_PREFIX + "key-exchange-groups") + .transformer((v, c) -> HybridKeyExchange.isEnabled() ? HybridKeyExchange.getEnabledGroups() : null) + .build() + )); + mappers.addAll(List.of( fromOption(HttpOptions.HTTPS_CIPHER_SUITES) .to(TLS_PREFIX + "cipher-suites") diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ManagementPropertyMappers.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ManagementPropertyMappers.java index 7423d35e90e..6e06f147d09 100644 --- a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ManagementPropertyMappers.java +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/configuration/mappers/ManagementPropertyMappers.java @@ -28,6 +28,7 @@ import org.keycloak.config.Option; import org.keycloak.config.OptionBuilder; import org.keycloak.quarkus.runtime.configuration.Configuration; +import org.keycloak.quarkus.runtime.tls.HybridKeyExchange; import io.smallrye.config.ConfigSourceInterceptorContext; @@ -49,6 +50,16 @@ public class ManagementPropertyMappers implements PropertyMapperGrouping { .synthetic() .build(); + private static final Option SYNTHETIC_MGMT_TLS_PQC_ENFORCEMENT_POLICY = new OptionBuilder<>("https-management-tls-pqc-enforcement-policy-hidden", String.class) + .buildTime(false) + .synthetic() + .build(); + + private static final Option SYNTHETIC_MGMT_TLS_KEY_EXCHANGE_GROUPS = new OptionBuilder<>("https-management-tls-key-exchange-groups-hidden", String.class) + .buildTime(false) + .synthetic() + .build(); + @Override public List> getPropertyMappers() { var mappers = new ArrayList>(); @@ -95,6 +106,17 @@ public List> getPropertyMappers() { .build() ); + mappers.addAll(List.of( + fromOption(SYNTHETIC_MGMT_TLS_PQC_ENFORCEMENT_POLICY) + .to(MGMT_TLS_PREFIX + "pqc-enforcement-policy") + .transformer((v, c) -> HybridKeyExchange.isEnabled() ? HybridKeyExchange.PQC_ENFORCEMENT_POLICY : null) + .build(), + fromOption(SYNTHETIC_MGMT_TLS_KEY_EXCHANGE_GROUPS) + .to(MGMT_TLS_PREFIX + "key-exchange-groups") + .transformer((v, c) -> HybridKeyExchange.isEnabled() ? HybridKeyExchange.getEnabledGroups() : null) + .build() + )); + mappers.addAll(List.of( fromOption(ManagementOptions.HTTPS_MANAGEMENT_CIPHER_SUITES) .isEnabled(ManagementPropertyMappers::isInheritedScheme, HTTP_MANAGEMENT_SCHEME_IS_INHERITED) diff --git a/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/tls/HybridKeyExchange.java b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/tls/HybridKeyExchange.java new file mode 100644 index 00000000000..50c0c771b9f --- /dev/null +++ b/quarkus/runtime/src/main/java/org/keycloak/quarkus/runtime/tls/HybridKeyExchange.java @@ -0,0 +1,152 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.keycloak.quarkus.runtime.tls; + +import java.util.List; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.TrustManager; + +import org.keycloak.common.Profile; + +import io.vertx.core.net.PqcEnforcementPolicy; +import io.vertx.core.net.impl.SslEngineUtils; +import org.jboss.logging.Logger; + +/** + * Support for post-quantum hybrid key exchange in TLS, controlled by the {@link Profile.Feature#TLS_HYBRID_KEY_EXCHANGE} feature. + *

+ * The key exchange groups are the ones Vert.x, and therefore Quarkus, uses for the {@value #PQC_ENFORCEMENT_POLICY} policy, + * so incoming and outgoing connections use the same groups. + *

+ * Outgoing connections all end up in JSSE, so they are covered by the JVM-wide {@value #NAMED_GROUPS_PROPERTY} property. + * Incoming connections are configured via the Quarkus TLS registry, see {@link #PQC_ENFORCEMENT_POLICY} and {@link #getEnabledGroups()}. + */ +public final class HybridKeyExchange { + + private static final Logger logger = Logger.getLogger(HybridKeyExchange.class); + + /** + * JVM-wide property defining the enabled TLS named groups in the order of preference. + */ + public static final String NAMED_GROUPS_PROPERTY = "jdk.tls.namedGroups"; + + /** + * Quarkus TLS registry policy for incoming connections. Hybrid groups are preferred, but clients not supporting + * them can still connect using a classical key exchange. + */ + public static final String PQC_ENFORCEMENT_POLICY = "client-negotiated"; + + private static volatile List enabledGroups; + + private HybridKeyExchange() { + } + + public static boolean isEnabled() { + return Profile.isFeatureEnabled(Profile.Feature.TLS_HYBRID_KEY_EXCHANGE); + } + + /** + * @return the hybrid groups as defined by Vert.x + */ + public static List getHybridGroups() { + return SslEngineUtils.getPqCompliantGroups(); + } + + /** + * @return the hybrid groups followed by the classical ones, in the order of preference, as Vert.x defaults to for + * the {@value #PQC_ENFORCEMENT_POLICY} policy + */ + public static List getGroups() { + return SslEngineUtils.resolveKeyExchangeGroups(null, PqcEnforcementPolicy.CLIENT_NEGOTIATED); + } + + /** + * Makes the hybrid groups preferred by all TLS connections using JSSE. Has to be called before JSSE is initialized + * as the named groups are read only once. + */ + public static void configure() { + if (isUserDefined()) { + logger.infof("The '%s' system property is set to '%s'. It is used instead of the groups of the '%s' feature.", + NAMED_GROUPS_PROPERTY, System.getProperty(NAMED_GROUPS_PROPERTY), Profile.Feature.TLS_HYBRID_KEY_EXCHANGE.getKey()); + return; + } + System.setProperty(NAMED_GROUPS_PROPERTY, String.join(",", getGroups())); + } + + /** + * Verifies the TLS provider in use offers at least one hybrid group. Has to be called after {@link #configure()} + * and after the crypto provider is set, as it initializes JSSE. + * + * @throws IllegalStateException if no hybrid group is available + */ + public static void verify() { + List groups = getEffectiveDefaultGroups(); + if (groups.stream().noneMatch(HybridKeyExchange::isHybridGroup)) { + throw new IllegalStateException( + "The '%s' feature is enabled, but none of the hybrid TLS key exchange groups %s is available. %s. Use a Java runtime supporting them, for example OpenJDK 25.0.5 or newer, and make sure they are not excluded by the '%s' system property. The feature is not supported in FIPS mode." + .formatted(Profile.Feature.TLS_HYBRID_KEY_EXCHANGE.getKey(), getHybridGroups(), + groups.isEmpty() ? "The available groups cannot be determined" : "Available groups: " + groups, + NAMED_GROUPS_PROPERTY)); + } + setEnabledGroups(groups); + logger.infof("Hybrid key exchange is preferred for TLS connections. Enabled groups: %s", String.join(", ", groups)); + } + + /** + * @return the comma-separated named groups enabled for TLS connections, or {@code null} if not verified yet + */ + public static String getEnabledGroups() { + List groups = enabledGroups; + return groups == null ? null : String.join(",", groups); + } + + /** + * Set by {@link #verify()}. Public only for testing purposes. + */ + public static void setEnabledGroups(List groups) { + enabledGroups = groups == null ? null : List.copyOf(groups); + } + + private static boolean isUserDefined() { + String groups = System.getProperty(NAMED_GROUPS_PROPERTY); + return groups != null && !groups.isBlank(); + } + + private static boolean isHybridGroup(String group) { + return getHybridGroups().stream().anyMatch(group::equalsIgnoreCase); + } + + /** + * @return the named groups enabled by default in the TLS provider in use, or an empty list if they cannot be determined + */ + private static List getEffectiveDefaultGroups() { + try { + // Not using the default SSLContext to not initialize it before the system truststore is configured + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, new TrustManager[0], null); + // SSLParameters.getNamedGroups() is available since Java 20 + String[] groups = (String[]) SSLParameters.class.getMethod("getNamedGroups").invoke(context.getDefaultSSLParameters()); + return groups == null ? List.of() : List.of(groups); + } catch (NoSuchMethodException e) { + return List.of(); + } catch (Exception e) { + throw new IllegalStateException("Unable to determine the available TLS key exchange groups", e); + } + } +} diff --git a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ConfigurationTest.java b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ConfigurationTest.java index 28b79a71bc3..1b15d97dd14 100644 --- a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ConfigurationTest.java +++ b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ConfigurationTest.java @@ -21,6 +21,7 @@ import java.nio.file.FileSystems; import java.util.Arrays; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.ServiceConfigurationError; import java.util.Set; @@ -34,6 +35,7 @@ import org.keycloak.quarkus.runtime.configuration.mappers.DatabasePropertyMappers; import org.keycloak.quarkus.runtime.configuration.mappers.HttpPropertyMappers; import org.keycloak.quarkus.runtime.configuration.mappers.ManagementPropertyMappers; +import org.keycloak.quarkus.runtime.tls.HybridKeyExchange; import org.keycloak.quarkus.runtime.vault.FilesKeystoreVaultProviderFactory; import org.keycloak.quarkus.runtime.vault.FilesPlainTextVaultProviderFactory; import org.keycloak.spi.infinispan.CacheEmbeddedConfigProviderSpi; @@ -1169,6 +1171,29 @@ public void testTlsConfigNameWiring() { assertNull(config.getConfigValue("quarkus.http.tls-configuration-name").getValue()); } + @Test + public void testTlsHybridKeyExchange() { + HybridKeyExchange.setEnabledGroups(List.of("X25519MLKEM768", "x25519")); + try { + ConfigArgsConfigSource.setCliArgs("--features=tls-hybrid-key-exchange", "--https-certificate-file=/cert.pem", "--https-certificate-key-file=/key.pem"); + initConfig(); + assertExternalConfig(Map.of( + HttpPropertyMappers.TLS_PREFIX + "pqc-enforcement-policy", "client-negotiated", + HttpPropertyMappers.TLS_PREFIX + "key-exchange-groups", "X25519MLKEM768,x25519" + )); + } finally { + HybridKeyExchange.setEnabledGroups(null); + } + } + + @Test + public void testTlsHybridKeyExchangeFeatureDisabled() { + ConfigArgsConfigSource.setCliArgs("--https-certificate-file=/cert.pem", "--https-certificate-key-file=/key.pem"); + initConfig(); + assertExternalConfigNull(HttpPropertyMappers.TLS_PREFIX + "pqc-enforcement-policy"); + assertExternalConfigNull(HttpPropertyMappers.TLS_PREFIX + "key-exchange-groups"); + } + @Test public void testHttpPemCertKeyMapping() { ConfigArgsConfigSource.setCliArgs("--https-certificate-file=/my/cert.pem", "--https-certificate-key-file=/my/key.pem"); diff --git a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ManagementConfigurationTest.java b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ManagementConfigurationTest.java index 2c6b313f0d3..1b97c9237be 100644 --- a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ManagementConfigurationTest.java +++ b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/configuration/ManagementConfigurationTest.java @@ -16,12 +16,14 @@ */ package org.keycloak.quarkus.runtime.configuration; +import java.util.List; import java.util.Map; import org.keycloak.quarkus.runtime.cli.command.Build; import org.keycloak.quarkus.runtime.configuration.mappers.HttpPropertyMappers; import org.keycloak.quarkus.runtime.configuration.mappers.ManagementPropertyMappers; import org.keycloak.quarkus.runtime.configuration.mappers.PropertyMappers; +import org.keycloak.quarkus.runtime.tls.HybridKeyExchange; import org.junit.Test; @@ -394,6 +396,28 @@ public void managementTlsConfigNameWithOwnCerts() { assertManagementHttpsEnabled(true); } + @Test + public void managementTlsHybridKeyExchange() { + makeInterfaceOccupied(); + putEnvVars(Map.of( + "KC_FEATURES", "tls-hybrid-key-exchange", + "KC_HTTPS_CERTIFICATE_FILE", "/cert.pem", + "KC_HTTPS_CERTIFICATE_KEY_FILE", "/key.pem" + )); + initConfig(); + HybridKeyExchange.setEnabledGroups(List.of("X25519MLKEM768", "x25519")); + try { + assertExternalConfig(Map.of( + ManagementPropertyMappers.MGMT_TLS_PREFIX + "pqc-enforcement-policy", "client-negotiated", + ManagementPropertyMappers.MGMT_TLS_PREFIX + "key-exchange-groups", "X25519MLKEM768,x25519", + HttpPropertyMappers.TLS_PREFIX + "pqc-enforcement-policy", "client-negotiated", + HttpPropertyMappers.TLS_PREFIX + "key-exchange-groups", "X25519MLKEM768,x25519" + )); + } finally { + HybridKeyExchange.setEnabledGroups(null); + } + } + @Test public void managementTlsConfigNameDisabledForHttpScheme() { makeInterfaceOccupied(); diff --git a/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/tls/HybridKeyExchangeTest.java b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/tls/HybridKeyExchangeTest.java new file mode 100644 index 00000000000..f5f6130e27b --- /dev/null +++ b/quarkus/runtime/src/test/java/org/keycloak/quarkus/runtime/tls/HybridKeyExchangeTest.java @@ -0,0 +1,62 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.keycloak.quarkus.runtime.tls; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class HybridKeyExchangeTest { + + private String originalGroups; + + @Before + public void storeGroups() { + originalGroups = System.getProperty(HybridKeyExchange.NAMED_GROUPS_PROPERTY); + } + + @After + public void restoreGroups() { + if (originalGroups == null) { + System.clearProperty(HybridKeyExchange.NAMED_GROUPS_PROPERTY); + } else { + System.setProperty(HybridKeyExchange.NAMED_GROUPS_PROPERTY, originalGroups); + } + } + + @Test + public void hybridGroupsArePreferred() { + System.clearProperty(HybridKeyExchange.NAMED_GROUPS_PROPERTY); + + HybridKeyExchange.configure(); + + assertEquals("X25519MLKEM768,SecP256r1MLKEM768,SecP384r1MLKEM1024,X25519,secp256r1,x448,secp384r1,secp521r1", + System.getProperty(HybridKeyExchange.NAMED_GROUPS_PROPERTY)); + } + + @Test + public void userDefinedGroupsAreRespected() { + System.setProperty(HybridKeyExchange.NAMED_GROUPS_PROPERTY, "x25519,X25519MLKEM768"); + + HybridKeyExchange.configure(); + + assertEquals("x25519,X25519MLKEM768", System.getProperty(HybridKeyExchange.NAMED_GROUPS_PROPERTY)); + } +} diff --git a/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/FakeTlsServer.java b/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/FakeTlsServer.java new file mode 100644 index 00000000000..bdbfcc21601 --- /dev/null +++ b/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/FakeTlsServer.java @@ -0,0 +1,375 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.keycloak.it.cli.dist; + +import java.io.ByteArrayOutputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetAddress; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.KeyStore; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.KeyManagerFactory; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLSocket; + +/** + * A server accepting TLS connections and recording the key exchange groups offered by the client and the group + * negotiated. It does not speak any application protocol, apart from what a client needs before it starts the TLS + * handshake, so the client fails once the handshake is over. + *

+ * The server enables both classical and hybrid groups, with the classical ones first, so a hybrid group is negotiated + * only if the client prefers it. + *

+ * As JSSE does not expose the negotiated group, the connections are passed through to a regular TLS server and the + * hello messages, which are not encrypted, are read on the way. + */ +public class FakeTlsServer implements AutoCloseable { + + /** + * What the client and the server exchange before the TLS handshake. + */ + public enum Preamble { + /** TLS from the first byte */ + NONE, + /** The SSLRequest of the client answered with 'S' */ + POSTGRESQL, + /** The initial handshake of the server followed by the SSLRequest of the client, used by MySQL and MariaDB */ + MYSQL + } + + /** + * @param offeredGroups the groups supported by the client, in the order of its preference + * @param keyShares the groups the client sent a key share for + * @param negotiatedGroup the group selected by the server, {@code null} if the server refused the handshake + */ + public record Handshake(List offeredGroups, List keyShares, String negotiatedGroup) { + } + + public static final List HYBRID_GROUPS = List.of("X25519MLKEM768", "SecP256r1MLKEM768", "SecP384r1MLKEM1024"); + + private static final String[] SERVER_GROUPS = {"x25519", "secp256r1", "X25519MLKEM768", "SecP256r1MLKEM768", "SecP384r1MLKEM1024"}; + + private static final Map GROUP_NAMES = Map.ofEntries( + Map.entry(0x0017, "secp256r1"), Map.entry(0x0018, "secp384r1"), Map.entry(0x0019, "secp521r1"), + Map.entry(0x001d, "x25519"), Map.entry(0x001e, "x448"), + Map.entry(0x0100, "ffdhe2048"), Map.entry(0x0101, "ffdhe3072"), Map.entry(0x0102, "ffdhe4096"), + Map.entry(0x0103, "ffdhe6144"), Map.entry(0x0104, "ffdhe8192"), + Map.entry(0x11eb, "SecP256r1MLKEM768"), Map.entry(0x11ec, "X25519MLKEM768"), Map.entry(0x11ed, "SecP384r1MLKEM1024")); + + private static final String HOST = "127.0.0.1"; + private static final String KEYSTORE = "/server.keystore"; + private static final char[] KEYSTORE_PASSWORD = "password".toCharArray(); + private static final int TIMEOUT_MILLIS = 10000; + + private static final int RECORD_HEADER_LENGTH = 5; + private static final int RECORD_HANDSHAKE = 22; + private static final int HANDSHAKE_CLIENT_HELLO = 1; + private static final int HANDSHAKE_SERVER_HELLO = 2; + private static final int EXTENSION_SUPPORTED_GROUPS = 10; + private static final int EXTENSION_KEY_SHARE = 51; + + private final Preamble preamble; + private final ServerSocket frontend; + private final SSLServerSocket backend; + private final BlockingQueue handshakes = new LinkedBlockingQueue<>(); + private final ExecutorService executor = Executors.newCachedThreadPool(runnable -> { + Thread thread = new Thread(runnable, "fake-tls-server"); + thread.setDaemon(true); + return thread; + }); + + public FakeTlsServer() { + this(Preamble.NONE); + } + + public FakeTlsServer(Preamble preamble) { + this.preamble = preamble; + try { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + try (InputStream is = FakeTlsServer.class.getResourceAsStream(KEYSTORE)) { + keyStore.load(is, KEYSTORE_PASSWORD); + } + KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); + kmf.init(keyStore, KEYSTORE_PASSWORD); + SSLContext context = SSLContext.getInstance("TLS"); + context.init(kmf.getKeyManagers(), null, null); + + backend = (SSLServerSocket) context.getServerSocketFactory().createServerSocket(0, 50, InetAddress.getByName(HOST)); + SSLParameters parameters = backend.getSSLParameters(); + parameters.setProtocols(new String[] {"TLSv1.3"}); + // SSLParameters.setNamedGroups() is available since Java 20 + SSLParameters.class.getMethod("setNamedGroups", String[].class).invoke(parameters, (Object) SERVER_GROUPS); + backend.setSSLParameters(parameters); + + frontend = new ServerSocket(0, 50, InetAddress.getByName(HOST)); + } catch (Exception e) { + throw new IllegalStateException("Failed to start the server", e); + } + executor.submit(this::acceptBackend); + executor.submit(this::acceptFrontend); + } + + public String getHost() { + return HOST; + } + + public int getPort() { + return frontend.getLocalPort(); + } + + /** + * @return the first handshake recorded, or {@code null} if no client started one in time + */ + public Handshake awaitHandshake(Duration timeout) throws InterruptedException { + return handshakes.poll(timeout.toMillis(), TimeUnit.MILLISECONDS); + } + + @Override + public void close() throws IOException { + executor.shutdownNow(); + frontend.close(); + backend.close(); + } + + private void acceptBackend() { + while (!backend.isClosed()) { + try { + SSLSocket socket = (SSLSocket) backend.accept(); + executor.submit(() -> { + try (socket) { + socket.setSoTimeout(TIMEOUT_MILLIS); + socket.startHandshake(); + // nothing to say, waiting for the client to give up + socket.getInputStream().read(); + } catch (IOException ignored) { + // the client did not complete the handshake or closed the connection + } + }); + } catch (IOException ignored) { + // closed + } + } + } + + private void acceptFrontend() { + while (!frontend.isClosed()) { + try { + Socket client = frontend.accept(); + executor.submit(() -> serve(client)); + } catch (IOException ignored) { + // closed + } + } + } + + private void serve(Socket client) { + try (client; Socket server = new Socket(HOST, backend.getLocalPort())) { + client.setSoTimeout(TIMEOUT_MILLIS); + server.setSoTimeout(TIMEOUT_MILLIS); + exchangePreamble(client); + + ByteArrayOutputStream fromClient = new ByteArrayOutputStream(); + ByteArrayOutputStream fromServer = new ByteArrayOutputStream(); + boolean[] recorded = {false}; + Runnable record = () -> { + synchronized (recorded) { + if (recorded[0]) { + return; + } + byte[] clientHello = firstRecord(fromClient); + byte[] serverReply = firstRecord(fromServer); + if (clientHello != null && serverReply != null) { + recorded[0] = true; + handshakes.add(new Handshake( + groups(clientHello, HANDSHAKE_CLIENT_HELLO, EXTENSION_SUPPORTED_GROUPS), + groups(clientHello, HANDSHAKE_CLIENT_HELLO, EXTENSION_KEY_SHARE), + groups(serverReply, HANDSHAKE_SERVER_HELLO, EXTENSION_KEY_SHARE).stream().findFirst().orElse(null))); + } + } + }; + + var toServer = executor.submit(() -> pump(client, server, fromClient, record)); + pump(server, client, fromServer, record); + toServer.cancel(true); + } catch (Exception ignored) { + // the client gave up + } + } + + private void exchangePreamble(Socket client) throws IOException { + switch (preamble) { + case POSTGRESQL -> { + new DataInputStream(client.getInputStream()).readFully(new byte[8]); + client.getOutputStream().write('S'); + client.getOutputStream().flush(); + } + case MYSQL -> { + client.getOutputStream().write(mysqlInitialHandshake()); + client.getOutputStream().flush(); + DataInputStream in = new DataInputStream(client.getInputStream()); + byte[] header = new byte[4]; + in.readFully(header); + in.readFully(new byte[(header[0] & 0xff) | (header[1] & 0xff) << 8 | (header[2] & 0xff) << 16]); + } + default -> { + } + } + } + + /** + * A minimal initial handshake packet (protocol version 10) advertising TLS support. + */ + private static byte[] mysqlInitialHandshake() throws IOException { + int capabilities = 0x00000200 /* protocol 4.1 */ | 0x00000800 /* SSL */ | 0x00008000 /* secure connection */ | 0x00080000 /* plugin auth */; + + ByteArrayOutputStream payload = new ByteArrayOutputStream(); + payload.write(10); + payload.write("8.0.0\0".getBytes(StandardCharsets.US_ASCII)); + payload.write(new byte[] {1, 0, 0, 0}); // connection id + payload.write("12345678".getBytes(StandardCharsets.US_ASCII)); // auth plugin data, part 1 + payload.write(0); + payload.write(capabilities & 0xff); + payload.write(capabilities >> 8 & 0xff); + payload.write(33); // utf8 + payload.write(new byte[] {2, 0}); // status + payload.write(capabilities >> 16 & 0xff); + payload.write(capabilities >> 24 & 0xff); + payload.write(21); // auth plugin data length + payload.write(new byte[10]); + payload.write("123456789012\0".getBytes(StandardCharsets.US_ASCII)); // auth plugin data, part 2 + payload.write("mysql_native_password\0".getBytes(StandardCharsets.US_ASCII)); + + ByteArrayOutputStream packet = new ByteArrayOutputStream(); + packet.write(payload.size() & 0xff); + packet.write(payload.size() >> 8 & 0xff); + packet.write(payload.size() >> 16 & 0xff); + packet.write(0); // sequence id + payload.writeTo(packet); + return packet.toByteArray(); + } + + private static void pump(Socket from, Socket to, ByteArrayOutputStream recording, Runnable onData) { + byte[] buffer = new byte[8192]; + try { + InputStream in = from.getInputStream(); + OutputStream out = to.getOutputStream(); + int read; + while ((read = in.read(buffer)) != -1) { + synchronized (recording) { + recording.write(buffer, 0, read); + } + onData.run(); + out.write(buffer, 0, read); + out.flush(); + } + } catch (IOException ignored) { + // one of the sides closed the connection + } finally { + try { + to.close(); + } catch (IOException ignored) { + // already closed + } + } + } + + // ---- parsing of the hello messages ---- + + /** + * @return the first TLS record received, or {@code null} if it is not complete yet + */ + private static byte[] firstRecord(ByteArrayOutputStream recording) { + byte[] data; + synchronized (recording) { + data = recording.toByteArray(); + } + if (data.length < RECORD_HEADER_LENGTH) { + return null; + } + int length = RECORD_HEADER_LENGTH + ((data[3] & 0xff) << 8 | data[4] & 0xff); + return data.length < length ? null : java.util.Arrays.copyOf(data, length); + } + + /** + * @return the groups in the given extension of a hello message, an empty list if the record is not such a message + */ + private static List groups(byte[] record, int handshakeType, int extensionType) { + List groups = new ArrayList<>(); + ByteBuffer buffer = ByteBuffer.wrap(record); + if (buffer.get() != RECORD_HANDSHAKE) { + return groups; + } + buffer.position(RECORD_HEADER_LENGTH); + if (buffer.get() != handshakeType) { + return groups; + } + skip(buffer, 3 /* length */ + 2 /* version */ + 32 /* random */); + skip(buffer, buffer.get() & 0xff); // session id + if (handshakeType == HANDSHAKE_CLIENT_HELLO) { + skip(buffer, buffer.getShort() & 0xffff); // cipher suites + skip(buffer, buffer.get() & 0xff); // compression methods + } else { + skip(buffer, 2 /* cipher suite */ + 1 /* compression method */); + } + + int extensionsEnd = (buffer.getShort() & 0xffff) + buffer.position(); + while (buffer.position() < extensionsEnd) { + int type = buffer.getShort() & 0xffff; + int end = (buffer.getShort() & 0xffff) + buffer.position(); + if (type == extensionType) { + if (handshakeType == HANDSHAKE_SERVER_HELLO) { + // the selected group, followed by the key share unless it is a HelloRetryRequest + groups.add(groupName(buffer.getShort())); + } else { + skip(buffer, 2); // length of the list + while (buffer.position() < end) { + groups.add(groupName(buffer.getShort())); + if (extensionType == EXTENSION_KEY_SHARE) { + skip(buffer, buffer.getShort() & 0xffff); // key share + } + } + } + } + buffer.position(end); + } + return groups; + } + + private static void skip(ByteBuffer buffer, int length) { + buffer.position(buffer.position() + length); + } + + private static String groupName(short id) { + return GROUP_NAMES.getOrDefault(id & 0xffff, "0x%04x".formatted(id & 0xffff)); + } +} diff --git a/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/TlsHybridKeyExchangeDistTest.java b/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/TlsHybridKeyExchangeDistTest.java new file mode 100644 index 00000000000..b5d8780fc52 --- /dev/null +++ b/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/TlsHybridKeyExchangeDistTest.java @@ -0,0 +1,136 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.keycloak.it.cli.dist; + +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLException; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; + +import org.keycloak.it.junit5.extension.CLIResult; +import org.keycloak.it.junit5.extension.DistributionTest; +import org.keycloak.it.junit5.extension.RawDistOnly; +import org.keycloak.it.junit5.extension.StopServer.Mode; +import org.keycloak.it.junit5.extension.WithEnvVars; + +import io.quarkus.test.junit.main.Launch; +import io.quarkus.test.junit.main.LaunchResult; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledIf; +import org.junit.jupiter.api.condition.EnabledIf; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@DistributionTest(stopServer = Mode.MANUAL, + enableTls = true, + defaultOptions = {"--db=dev-file", "--health-enabled=true", "--features=tls-hybrid-key-exchange"}) +@RawDistOnly(reason = "We do not test TLS in containers") +public class TlsHybridKeyExchangeDistTest { + + private static final String HYBRID_GROUP = "X25519MLKEM768"; + private static final String CLASSICAL_GROUP = "x25519"; + + @Test + @EnabledIf("isHybridKeyExchangeSupported") + @Launch({"start-dev"}) + void hybridKeyExchangePreferred(LaunchResult result) throws Exception { + CLIResult cliResult = (CLIResult) result; + cliResult.assertMessage("Hybrid key exchange is preferred for TLS connections. Enabled groups: " + HYBRID_GROUP); + cliResult.assertStartedDevMode(); + + for (int port : new int[] {8443, 9000}) { + // the handshake can succeed only if the server accepts the single group offered by the client + assertHandshake(port, HYBRID_GROUP); + // not enabled by default in the Java runtime, unlike X25519MLKEM768 + assertHandshake(port, "SecP256r1MLKEM768"); + assertHandshake(port, CLASSICAL_GROUP); + } + } + + @Test + @EnabledIf("isHybridKeyExchangeSupported") + @WithEnvVars({"JAVA_OPTS_APPEND", "-Djdk.tls.namedGroups=secp256r1," + HYBRID_GROUP}) + @Launch({"start-dev"}) + void userDefinedGroupsUsed(LaunchResult result) throws Exception { + CLIResult cliResult = (CLIResult) result; + cliResult.assertMessage("Hybrid key exchange is preferred for TLS connections. Enabled groups: secp256r1, " + HYBRID_GROUP); + cliResult.assertStartedDevMode(); + + for (int port : new int[] {8443, 9000}) { + assertHandshake(port, HYBRID_GROUP); + assertHandshake(port, "secp256r1"); + assertThrows(SSLException.class, () -> assertHandshake(port, CLASSICAL_GROUP)); + } + } + + @Test + @DisabledIf("isHybridKeyExchangeSupported") + @Launch({"start-dev"}) + void failsWhenHybridKeyExchangeNotSupported(LaunchResult result) { + CLIResult cliResult = (CLIResult) result; + cliResult.assertError("The 'tls-hybrid-key-exchange' feature is enabled, but none of the hybrid TLS key exchange groups"); + } + + static boolean isHybridKeyExchangeSupported() { + try { + SSLParameters parameters = SSLContext.getDefault().getDefaultSSLParameters(); + // SSLParameters.getNamedGroups() is available since Java 20 + String[] groups = (String[]) SSLParameters.class.getMethod("getNamedGroups").invoke(parameters); + return groups != null && Arrays.asList(groups).contains(HYBRID_GROUP); + } catch (Exception e) { + return false; + } + } + + private static void assertHandshake(int port, String group) throws Exception { + SSLContext context = SSLContext.getInstance("TLS"); + context.init(null, new TrustManager[] {new TrustAllManager()}, new SecureRandom()); + + try (SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket("localhost", port)) { + SSLParameters parameters = socket.getSSLParameters(); + parameters.setProtocols(new String[] {"TLSv1.3"}); + SSLParameters.class.getMethod("setNamedGroups", String[].class).invoke(parameters, (Object) new String[] {group}); + socket.setSSLParameters(parameters); + + socket.startHandshake(); + + assertEquals("TLSv1.3", socket.getSession().getProtocol()); + } + } + + private static class TrustAllManager implements X509TrustManager { + @Override + public void checkClientTrusted(X509Certificate[] chain, String authType) { + } + + @Override + public void checkServerTrusted(X509Certificate[] chain, String authType) { + } + + @Override + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + } +} diff --git a/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/TlsHybridKeyExchangeOutgoingDistTest.java b/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/TlsHybridKeyExchangeOutgoingDistTest.java new file mode 100644 index 00000000000..7a9f395210b --- /dev/null +++ b/quarkus/tests/integration/src/test/java/org/keycloak/it/cli/dist/TlsHybridKeyExchangeOutgoingDistTest.java @@ -0,0 +1,203 @@ +/* + * Copyright 2026 Red Hat, Inc. and/or its affiliates + * and other contributors as indicated by the @author tags. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.keycloak.it.cli.dist; + +import java.time.Duration; +import java.util.List; +import java.util.Map; + +import org.keycloak.it.cli.dist.FakeTlsServer.Handshake; +import org.keycloak.it.cli.dist.FakeTlsServer.Preamble; +import org.keycloak.it.junit5.extension.DistributionTest; +import org.keycloak.it.junit5.extension.RawDistOnly; +import org.keycloak.it.junit5.extension.StopServer.Mode; +import org.keycloak.it.junit5.extension.WithEnvVars; +import org.keycloak.it.utils.KeycloakDistribution; + +import io.quarkus.test.junit.main.Launch; +import io.restassured.http.ContentType; +import io.restassured.specification.RequestSpecification; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIf; + +import static io.restassured.RestAssured.given; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +/** + * Makes the server connect to a {@link FakeTlsServer} using the clients it has for outgoing TLS connections, and checks + * each of them prefers the hybrid key exchange groups. + */ +@DistributionTest(stopServer = Mode.MANUAL) +@RawDistOnly(reason = "The server needs to connect to the test") +@EnabledIf("org.keycloak.it.cli.dist.TlsHybridKeyExchangeDistTest#isHybridKeyExchangeSupported") +@WithEnvVars({"KC_BOOTSTRAP_ADMIN_USERNAME", TlsHybridKeyExchangeOutgoingDistTest.ADMIN, "KC_BOOTSTRAP_ADMIN_PASSWORD", TlsHybridKeyExchangeOutgoingDistTest.ADMIN}) +public class TlsHybridKeyExchangeOutgoingDistTest { + + static final String ADMIN = "admin"; + + private static final String FEATURE = "--features=tls-hybrid-key-exchange"; + private static final String SERVER_URL = "http://localhost:8080"; + private static final String ADMIN_URL = SERVER_URL + "/admin/realms/master"; + + /** + * The groups the feature enables, in the order of preference. + */ + private static final List FEATURE_GROUPS = List.of("X25519MLKEM768", "SecP256r1MLKEM768", "SecP384r1MLKEM1024", + "x25519", "secp256r1", "x448", "secp384r1", "secp521r1"); + + private static final Duration CONNECT_TIMEOUT = Duration.ofSeconds(30); + // includes the time needed to build and start the server + private static final Duration STARTUP_TIMEOUT = Duration.ofMinutes(3); + + // ---- connections made by a running server ---- + + @Test + @Launch({"start-dev", FEATURE}) + void httpClient() throws Exception { + try (FakeTlsServer server = new FakeTlsServer()) { + importIdentityProviderConfig(server); + assertHybridPreferred(server.awaitHandshake(CONNECT_TIMEOUT)); + } + } + + @Test + @Launch({"start-dev", FEATURE + ",http-client:v2"}) + void httpClientV2() throws Exception { + try (FakeTlsServer server = new FakeTlsServer()) { + importIdentityProviderConfig(server); + assertHybridPreferred(server.awaitHandshake(CONNECT_TIMEOUT)); + } + } + + @Test + @Launch({"start-dev", FEATURE}) + void smtp() throws Exception { + try (FakeTlsServer server = new FakeTlsServer()) { + // the test email is sent to the user making the request + String adminId = admin().get(ADMIN_URL + "/users?username=" + ADMIN).jsonPath().getString("[0].id"); + admin().body(Map.of("username", ADMIN, "email", "admin@localhost")).put(ADMIN_URL + "/users/" + adminId).then().statusCode(204); + + admin().body(Map.of("host", server.getHost(), "port", String.valueOf(server.getPort()), "ssl", "true", "from", "keycloak@localhost")) + .post(ADMIN_URL + "/testSMTPConnection"); + assertHybridPreferred(server.awaitHandshake(CONNECT_TIMEOUT)); + } + } + + @Test + @Launch({"start-dev", FEATURE}) + void ldap() throws Exception { + try (FakeTlsServer server = new FakeTlsServer()) { + admin().body(Map.of("action", "testConnection", "connectionUrl", "ldaps://" + server.getHost() + ":" + server.getPort(), + "useTruststoreSpi", "always", "authType", "none", "connectionTimeout", "5000")) + .post(ADMIN_URL + "/testLDAPConnection"); + assertHybridPreferred(server.awaitHandshake(CONNECT_TIMEOUT)); + } + } + + /** + * Makes sure the assertions can fail, as the Java runtime can prefer a hybrid group by default. + */ + @Test + @Launch({"start-dev"}) + void featureDisabled() throws Exception { + try (FakeTlsServer server = new FakeTlsServer()) { + importIdentityProviderConfig(server); + Handshake handshake = server.awaitHandshake(CONNECT_TIMEOUT); + assertNotNull(handshake, "The server did not connect"); + assertNotEquals(FEATURE_GROUPS, handshake.offeredGroups()); + } + } + + // ---- connections made when the server starts, which then fails as the peer is not a real one ---- + + @Test + void postgresql(KeycloakDistribution dist) throws Exception { + assertHybridPreferredOnStartup(dist, Preamble.POSTGRESQL, "postgres", "postgresql"); + } + + @Test + void mariadb(KeycloakDistribution dist) throws Exception { + assertHybridPreferredOnStartup(dist, Preamble.MYSQL, "mariadb", "mariadb"); + } + + @Test + void mysql(KeycloakDistribution dist) throws Exception { + assertHybridPreferredOnStartup(dist, Preamble.MYSQL, "mysql", "mysql"); + } + + @Test + void infinispanHotRod(KeycloakDistribution dist) throws Exception { + try (FakeTlsServer server = new FakeTlsServer()) { + assertHybridPreferredOnStartup(dist, server, "start-dev", FEATURE + ",multi-site", + "--cache-remote-host=" + server.getHost(), "--cache-remote-port=" + server.getPort(), + "--cache-remote-username=keycloak", "--cache-remote-password=keycloak", "--cache-remote-tls-enabled=true"); + } + } + + @Test + void syslog(KeycloakDistribution dist) throws Exception { + try (FakeTlsServer server = new FakeTlsServer()) { + assertHybridPreferredOnStartup(dist, server, "start-dev", FEATURE, "--log=console,syslog", + "--log-syslog-endpoint=" + server.getHost() + ":" + server.getPort(), "--log-syslog-protocol=ssl-tcp"); + } + } + + private static void assertHybridPreferredOnStartup(KeycloakDistribution dist, Preamble preamble, String vendor, String jdbcScheme) throws Exception { + try (FakeTlsServer server = new FakeTlsServer(preamble)) { + assertHybridPreferredOnStartup(dist, server, "start-dev", FEATURE, "--db=" + vendor, + "--db-url=jdbc:" + jdbcScheme + "://" + server.getHost() + ":" + server.getPort() + "/keycloak", + "--db-username=keycloak", "--db-password=keycloak", "--db-tls-mode=verify-server"); + } + } + + private static void assertHybridPreferredOnStartup(KeycloakDistribution dist, FakeTlsServer server, String... arguments) throws Exception { + try { + dist.runKc(arguments); + assertHybridPreferred(server.awaitHandshake(STARTUP_TIMEOUT)); + } finally { + dist.stop(); + } + } + + // ---- helpers ---- + + private static void assertHybridPreferred(Handshake handshake) { + assertNotNull(handshake, "The server did not connect"); + assertEquals(FEATURE_GROUPS, handshake.offeredGroups(), "Groups offered by the server"); + assertTrue(FakeTlsServer.HYBRID_GROUPS.contains(handshake.keyShares().get(0)), "The first key share is not for a hybrid group: " + handshake); + assertTrue(FakeTlsServer.HYBRID_GROUPS.contains(handshake.negotiatedGroup()), "A hybrid group was not negotiated: " + handshake); + } + + /** + * Makes the server fetch the configuration of an identity provider from the given peer. + */ + private static void importIdentityProviderConfig(FakeTlsServer server) { + admin().body(Map.of("providerId", "oidc", "fromUrl", "https://" + server.getHost() + ":" + server.getPort() + "/.well-known/openid-configuration")) + .post(ADMIN_URL + "/identity-provider/import-config"); + } + + private static RequestSpecification admin() { + String token = given().formParam("grant_type", "password").formParam("client_id", "admin-cli") + .formParam("username", ADMIN).formParam("password", ADMIN) + .post(SERVER_URL + "/realms/master/protocol/openid-connect/token") + .then().statusCode(200).extract().jsonPath().getString("access_token"); + return given().auth().oauth2(token).contentType(ContentType.JSON); + } +}