8000 Support system truststore reloading by michalvavrik · Pull Request #52520 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ public void generatedTruststoreIsReadWithItsWriterProvider() throws Exception {
Properties originalProperties = (Properties) System.getProperties().clone();
try {
// when
TruststoreBuilder.setSystemTruststore(new String[] { bundle.getAbsolutePath() }, false,
temporaryFolder.getRoot().getAbsolutePath());
TruststoreBuilder.setAndGetSystemTruststore(new String[] { bundle.getAbsolutePath() }, false,
temporaryFolder.getRoot().getAbsolutePath(), null);
factory.init(new Config.SystemPropertiesScope("keycloak.truststore.file."));
KeyStore truststore = factory.create(null).getTruststore();

Expand Down
7 changes: 7 additions & 0 deletions docs/documentation/release_notes/topics/27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,10 @@ See the upgrading guide for details.
== Credential ID in credential update events

The `UPDATE_CREDENTIAL` events emitted by built-in required actions now carry the `credential_id` detail when a credential was created or updated in the {project_name} credential store, as the `REMOVE_CREDENTIAL` event already did. The detail is omitted when an external user-storage provider handles the update because there is no {project_name} credential ID to report.

= Configuring and Running

== Reloadable system truststore
// https://github.com/keycloak/keycloak/issues/51680

The system truststore can now be reloaded at runtime, so rotated CA certificates are picked up without restarting {project_name}. Set the new `--truststore-paths-reload-period` option to a duration and {project_name} periodically re-reads the certificates referenced by `--truststore-paths` and the automatically discovered CA certificates, and rebuilds the system truststore. Reloading is opt-in and disabled unless the option is set. For details, see <@links.server id="keycloak-truststore"/>.
27 changes: 25 additions & 2 deletions docs/guides/server/keycloak-truststore.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@
<@tmpl.guide
title="Configuring trusted certificates"
summary="Configure the {project_name} Truststore to communicate through TLS."
includedOptions="truststore-paths truststore-kubernetes-enabled tls-hostname-verifier">
includedOptions="truststore-paths truststore-paths-reload-period truststore-kubernetes-enabled tls-hostname-verifier">

When {project_name} communicates with external services or has an incoming connection through TLS, it has to validate the remote certificate in order to ensure it is connecting to a trusted server. This is necessary in order to prevent man-in-the-middle attacks.

The certificates of these clients or servers, or the CA that signed these certificates, must be put in a truststore. This truststore is then configured for use by {project_name}.

== Configuring the System Truststore

The existing Java default truststore certs will always be trusted. If you need additional certificates, which will be the case if you have self-signed or internal certificate authorities that are not recognized by the JRE, they can be included in the `conf/truststores` directory or subdirectories. The certs may be in PEM files, or PKCS12 files with extension `.p12`, `.pfx`, or `.pkcs12`. If in PKCS12, the certs must be unencrypted - meaning no password is expected.
The existing Java default truststore certs will always be trusted. If you need additional certificates, which will be the case if you have self-signed or internal certificate authorities that are not recognized by the JRE, they can be included in the `conf/truststores` directory or subdirectories. The certs may be in PEM files, or passwordless PKCS12 files with extension `.p12`, `.pfx`, or `.pkcs12`. Such a file must either have no MAC, or a MAC computed with an empty password; files that use a non-empty password are not supported.

If you need an alternative path, use the `--truststore-paths` option to specify additional files or directories where PEM or PKCS12 files are located. Paths are relative to where you launched {project_name}, so absolute paths are recommended instead. If a directory is specified, it will be recursively scanned for truststore files.

Expand All @@ -26,6 +26,29 @@ For example:

It is still possible to directly set your own `javax.net.ssl` truststore System properties, but it's recommended to use the `--truststore-paths` instead.

== Reloading the system truststore

By default, the system truststore is built once at startup and stays fixed for the lifetime of the server. To pick up rotated CA certificates without a restart - for example, when a certificate authority is renewed - set the `--truststore-paths-reload-period` option to a duration. Reloading is opt-in: when the option is unset, the system truststore is never reloaded automatically.

When set, {project_name} periodically re-reads the files and directories referenced by `--truststore-paths`, together with the automatically discovered default CA certificates (such as the Kubernetes and OpenShift cluster CAs), and rebuilds the system truststore. The period controls how quickly a certificate rotation is detected. Keep in mind that if you specify a directory path, any file change under that directory triggers a reload, even if the file is not a certificate.

For example, to reload the system truststore every hour:

<@kc.start parameters="--truststore-paths=/opt/truststore/myTrustStore.pem --truststore-paths-reload-period=1h" />

The reload does not apply to database (JDBC) connections, HTTP Client v2 connection, or to connections to a remote {jdgserver_name} server; these continue to use the trust material loaded at startup.

The HTTPS and management interfaces adopt the reloaded system truststore when they use it to validate client certificates. That is the case when mutual TLS is enabled with `--https-client-auth` and no dedicated truststore is set with `--https-trust-store-file`, or with `--https-management-trust-store-file` for the management interface. A dedicated truststore is reloaded according to `--https-certificates-reload-period` instead.

Removing a certificate takes effect for new connections only. Existing pooled or keep-alive connections keep using the trust established when they were opened, until those connections are closed.

To stop trusting certificates, delete their file from a directory listed in `--truststore-paths`, or remove them from a file listed in `--truststore-paths`.
Deleting a file or directory that is itself listed in `--truststore-paths` does not remove its certificates: the reload fails, and {project_name} logs a warning and keeps using the previously loaded system truststore.

Because a reload applies changes to the truststore without a restart, restrict write access to the files and directories referenced by `--truststore-paths` to trusted administrators.

TIP: It takes time for file changes to be detected and for all internal components to adopt the new truststore. To prevent rejected connections during this window, use an overlapping rotation strategy: add the new CA certificate alongside the old one, wait for the reload period and connection pools to cycle, and only then remove the old CA certificate.

== Cluster CA certificates (Kubernetes and OpenShift)

When running {project_name} on Kubernetes or OpenShift, the server will automatically include well-known cluster certificate authorities in the system truststore if they are present on the filesystem:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

import org.keycloak.common.enums.HostnameVerificationPolicy;

import static org.keycloak.config.OptionsUtil.DURATION_DESCRIPTION;

public class TruststoreOptions {

public static final Option<List<String>> TRUSTSTORE_PATHS = OptionBuilder.listOptionBuilder("truststore-paths", String.class)
Expand All @@ -24,4 +26,13 @@ public class TruststoreOptions {
.deprecatedValues("STRICT and WILDCARD have been deprecated, use DEFAULT instead.", HostnameVerificationPolicy.STRICT, HostnameVerificationPolicy.WILDCARD)
.build();

public static final String TRUSTSTORE_PATHS_RELOAD_PERIOD_KEY = "truststore-paths-reload-period";

public static final Option<String> TRUSTSTORE_PATHS_RELOAD_PERIOD = new OptionBuilder<>(TRUSTSTORE_PATHS_RELOAD_PERIOD_KEY, String.class)
.buildTime(true)
.category(OptionCategory.TRUSTSTORE)
Comment thread
michalvavrik marked this conversation as resolved.
Resolved
.description("Interval on which to reload the system truststore material referenced by the truststore-paths option and the automatically discovered CA certificates. "
+ DURATION_DESCRIPTION + " If not set, the system truststore is not reloaded automatically. When the reload period is configured, there must be at least one truststore source: a truststore-paths entry, a file under conf/truststores, or a discovered cluster CA certificate.")
.build();

}
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@
import org.keycloak.quarkus.runtime.integration.QuarkusKeycloakSessionFactory;
import org.keycloak.quarkus.runtime.integration.resteasy.KeycloakHandlerChainCustomizer;
import org.keycloak.quarkus.runtime.integration.resteasy.KeycloakTracingCustomizer;
import org.keycloak.quarkus.runtime.integration.tls.SystemTruststoreReload;
import org.keycloak.quarkus.runtime.integration.tls.SystemTruststoreReload.SystemTruststoreSourceAndKeystore;
import org.keycloak.quarkus.runtime.logging.ClearMappedDiagnosticContextFilter;
import org.keycloak.quarkus.runtime.services.RejectSourceMapFilter;
import org.keycloak.quarkus.runtime.services.health.BootstrapReadyHealthCheck;
Expand Down Expand Up @@ -129,6 +131,7 @@
import io.quarkus.arc.deployment.AnnotationsTransformerBuildItem;
import io.quarkus.arc.deployment.BuildTimeConditionBuildItem;
import io.quarkus.arc.deployment.SyntheticBeanBuildItem;
import io.quarkus.arc.processor.BuiltinScope;
import io.quarkus.bootstrap.logging.InitialConfigurator;
import io.quarkus.datasource.runtime.DataSourcesBuildTimeConfig;
import io.quarkus.deployment.IsDevelopment;
Expand Down Expand Up @@ -157,7 +160,9 @@
import io.quarkus.resteasy.reactive.server.spi.MethodScannerBuildItem;
import io.quarkus.resteasy.reactive.server.spi.PreExceptionMapperHandlerBuildItem;
import io.quarkus.runtime.LaunchMode;
import io.quarkus.runtime.RuntimeValue;
import io.quarkus.runtime.configuration.ConfigurationException;
import io.quarkus.tls.deployment.spi.TlsCertificateBuildItem;
import io.quarkus.vertx.http.deployment.FilterBuildItem;
import io.quarkus.vertx.http.deployment.HttpRootPathBuildItem;
import io.quarkus.vertx.http.deployment.ManagementInterfaceFilterBuildItem;
Expand Down Expand Up @@ -186,6 +191,7 @@
import org.jboss.resteasy.reactive.server.processor.scanning.MethodScanner;

import static org.keycloak.config.DatabaseOptions.DB;
import static org.keycloak.config.TruststoreOptions.TRUSTSTORE_PATHS_RELOAD_PERIOD;
import static org.keycloak.quarkus.runtime.Environment.getCurrentOrCreateFeatureProfile;
import static org.keycloak.quarkus.runtime.Providers.getProviderManager;
import static org.keycloak.quarkus.runtime.configuration.Configuration.getOptionalValue;
Expand All @@ -197,6 +203,8 @@
import static org.keycloak.representations.provider.ScriptProviderDescriptor.SAML_MAPPERS;
import static org.keycloak.theme.ClasspathThemeProviderFactory.KEYCLOAK_THEMES_JSON;



class KeycloakProcessor {

private static final Logger logger = Logger.getLogger(KeycloakProcessor.class);
Expand Down Expand Up @@ -381,7 +389,7 @@
logger.infof("Multiple datasources are specified: %s", String.join(", ", datasources));
}

if (transactionManagerConfig.unsafeMultipleLastResources()

Check warning on line 392 in quarkus/deployment/src/main/java/org/keycloak/quarkus/deployment/KeycloakProcessor.java

View workflow job for this annotation

GitHub Actions / Quarkus UT (ubuntu-latest)

unsafeMultipleLastResources() in io.quarkus.narayana.jta.runtime.TransactionManagerBuildTimeConfig has been deprecated and marked for removal
.orElse(UnsafeMultipleLastResourcesMode.DEFAULT) != UnsafeMultipleLastResourcesMode.FAIL) {
return;
}
Expand Down Expand Up @@ -1037,12 +1045,20 @@

@Consume(ProfileBuildItem.class)
@Produce(CryptoProviderInitBuildItem.class)
@Produce(TlsCertificateBuildItem.class) // prepare truststore before TLS registry is created
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void initCrypto(KeycloakRecorder recorder) {
void initCrypto(KeycloakRecorder recorder, BuildProducer<SyntheticBeanBuildItem> syntheticBeanProducer) {
FipsMode fipsMode = getFipsMode();
recorder.setCryptoProvider(fipsMode);
recorder.configureTruststore(fipsMode);
RuntimeValue<SystemTruststoreSourceAndKeystore> systemTruststoreSourceRuntimeValue = recorder.configureTruststore(fipsMode);
if (Configuration.getOptionalKcValue(TRUSTSTORE_PATHS_RELOAD_PERIOD).isPresent()) {
syntheticBeanProducer.produce(SyntheticBeanBuildItem.configure(SystemTruststoreReload.class)
.scope(BuiltinScope.SINGLETON.getInfo())
.unremovable()
.runtimeValue(recorder.createSystemTruststoreReloadBean(systemTruststoreSourceRuntimeValue))
.done());
}
}

private FipsMode getFipsMode() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@
import org.keycloak.quarkus.runtime.configuration.MicroProfileConfigProvider;
import org.keycloak.quarkus.runtime.configuration.mappers.HttpPropertyMappers;
import org.keycloak.quarkus.runtime.integration.QuarkusKeycloakSessionFactory;
import org.keycloak.quarkus.runtime.integration.tls.SystemTruststoreReload;
import org.keycloak.quarkus.runtime.integration.tls.SystemTruststoreReload.SystemTruststoreSourceAndKeystore;
import org.keycloak.quarkus.runtime.logging.KeycloakLogFilter;
import org.keycloak.quarkus.runtime.services.MisdirectedFilter;
import org.keycloak.quarkus.runtime.services.RejectNonNormalizedPathFilter;
Expand All @@ -73,6 +75,7 @@
import io.quarkus.hibernate.orm.runtime.integration.HibernateOrmIntegrationStaticInitListener;
import io.quarkus.runtime.RuntimeValue;
import io.quarkus.runtime.annotations.Recorder;
import io.quarkus.runtime.configuration.ConfigurationException;
import io.quarkus.vertx.http.runtime.security.SecurityHandlerPriorities;
import io.vertx.core.Handler;
import io.vertx.core.http.HttpHeaders;
Expand Down Expand Up @@ -153,6 +156,19 @@ public void setHibernateUnsupportedProperties(Set<String> keycloakDefaultUnsuppo
KeycloakLogFilter.setKeycloakDefaultUnsupportedProperties(keycloakDefaultUnsupportedProperties);
}

public RuntimeValue<SystemTruststoreReload> createSystemTruststoreReloadBean(RuntimeValue<SystemTruststoreSourceAndKeystore> systemTruststoreSourceRuntimeValue) {
final SystemTruststoreReload systemTruststoreReload;
if (systemTruststoreSourceRuntimeValue.getValue() == null) {
throw new ConfigurationException("""
Truststore reload period was configured, but there is no truststore source.
Either disable truststore reloading, or provide at least one truststore source.
""");
} else {
systemTruststoreReload = new SystemTruststoreReload(systemTruststoreSourceRuntimeValue.getValue());
}
return new RuntimeValue<>(systemTruststoreReload);
}

private record ManagementInterfaceItem(String path, String description, BooleanSupplier isEnabled) {
String getListItem() {
return "<li><a href=\"%s\">%s</a> - %s</li>".formatted(path, path, description);
Expand Down Expand Up @@ -187,7 +203,7 @@ private static void extractHost(Option<String> option, Set<String> allowedHosts)
}
}

public void configureTruststore(FipsMode fipsMode) {
public RuntimeValue<SystemTruststoreSourceAndKeystore> configureTruststore(FipsMode fipsMode) {
List<String> truststores = new ArrayList<>();
Configuration.getOptionalKcValue(TruststoreOptions.TRUSTSTORE_PATHS.getKey())
.ifPresent(s -> Stream.of(s.split(",")).forEach(truststores::add));
Expand All @@ -205,12 +221,15 @@ public void configureTruststore(FipsMode fipsMode) {
if (truststoresDir != null && truststoresDir.exists() && Optional.ofNullable(truststoresDir.list()).map(a -> a.length).orElse(0) > 0) {
truststores.add(truststoresDir.getAbsolutePath());
} else if (truststores.size() == 0) {
return; // nothing to configure, we'll just use the system default
return new RuntimeValue<>(); // nothing to configure, we'll just use the system default
}
Comment thread
michalvavrik marked this conversation as resolved.
Resolved

TruststoreFormat truststoreType = fipsMode == FipsMode.STRICT ? TruststoreFormat.BCFKS : null;

TruststoreBuilder.setSystemTruststore(truststores.toArray(String[]::new), true, dataDir.orElseThrow(), truststoreType);
String[] truststoresArray = truststores.toArray(String[]::new);
boolean reloadable = Configuration.getOptionalKcValue(TruststoreOptions.TRUSTSTORE_PATHS_RELOAD_PERIOD).isPresent();
return new RuntimeValue<>(SystemTruststoreReload.loadSystemTruststore(truststoresArray, true, dataDir.orElseThrow(),
truststoreType, reloadable));
}

public void configureLiquibase(Map<String, List<String>> services) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.function.Supplier;

import org.keycloak.common.Profile;
import org.keycloak.common.crypto.FipsMode;
Expand All @@ -17,12 +18,14 @@
import org.keycloak.config.OptionBuilder;
import org.keycloak.config.OptionsUtil;
import org.keycloak.config.SecurityOptions;
import org.keycloak.config.TruststoreOptions;
import org.keycloak.quarkus.runtime.Environment;
import org.keycloak.quarkus.runtime.Messages;
import org.keycloak.quarkus.runtime.cli.Picocli;
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.integration.tls.SystemTruststoreReload;

import io.quarkus.runtime.LaunchMode;
import io.quarkus.runtime.configuration.DurationConverter;
Expand Down Expand Up @@ -287,13 +290,32 @@ private void addTrustStoreMappers(List<PropertyMapper<?>> mappers) {
mappers.add(
fromOption(HttpOptions.HTTPS_TRUST_STORE_TYPE)
.mapFrom(HttpOptions.HTTPS_TRUST_STORE_TYPE, (name, value, ctx) ->
filterOtherStoreType(value, HttpOptions.HTTPS_TRUST_STORE_FILE))
systemTruststoreTypeOr(getReloadedSystemTruststoreType(), () -> filterOtherStoreType(value, HttpOptions.HTTPS_TRUST_STORE_FILE)))
// applies instead of the parent mapper when no truststore type is set
.transformer((name, value, ctx) -> systemTruststoreTypeOr(getReloadedSystemTruststoreType(), () -> value))
.to(TLS_PREFIX + "trust-store.other.type")
.paramLabel("type")
.build()
);
}

private static String getReloadedSystemTruststoreType() {
return getReloadedSystemTruststoreType(HttpOptions.HTTPS_TRUST_STORE_FILE, HttpOptions.HTTPS_CLIENT_AUTH, isHttpsEnabled());
}

static String getReloadedSystemTruststoreType(Option<File> trustStoreFileOption, Option<?> clientAuthOption, boolean tlsEnabled) {
boolean reloaded = getOptionalKcValue(TruststoreOptions.TRUSTSTORE_PATHS_RELOAD_PERIOD).filter(period -> !period.isBlank()).isPresent();
boolean clientAuth = getOptionalKcValue(clientAuthOption).filter(value -> !HttpOptions.ClientAuth.none.name().equals(value)).isPresent();
if (tlsEnabled && reloaded && clientAuth && getOptionalKcValue(trustStoreFileOption).isEmpty()) {
return SystemTruststoreReload.TRUST_STORE_TYPE;
}
return null;
}

static String systemTruststoreTypeOr(String systemTruststoreType, Supplier<String> otherwise) {
return systemTruststoreType != null ? systemTruststoreType : otherwise.get();
}

static String keyStoreSubPath(StoreType type, String property) {
return switch (type) {
case PKCS12 -> "key-store.p12." + property;
Expand Down
Loading
Loading
0