8000 Generate BCFKS truststore in strict FIPS by slaskawi · Pull Request #50149 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
10000
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
import javax.net.ssl.SSLSocketFactory;

import org.keycloak.common.util.KeystoreUtil.KeystoreFormat;
import org.keycloak.common.util.KeystoreUtil.TruststoreFormat;

/**
* Abstraction to handle differences between the APIs for non-fips and fips mode
Expand Down Expand Up @@ -97,6 +98,17 @@ public interface CryptoProvider {

KeyStore getKeyStore(KeystoreFormat format) throws KeyStoreException, NoSuchProviderException;

/**
* Get a Java KeyStore backed truststore for the given format.
* PEM is an input certificate format, not a generated Java KeyStore format.
*/
default KeyStore getTrustStore(TruststoreFormat format) throws KeyStoreException, NoSuchProviderException {
if (!format.isJavaTrustStore()) {
throw new KeyStoreException(format.name() + " is not a Java KeyStore truststore format");
}
return getKeyStore(KeystoreFormat.valueOf(format.name()));
}

/**
* @return Keystore types/algorithms supported by this CryptoProvider
*/
Expand All @@ -112,6 +124,37 @@ default Stream<KeystoreFormat> getSupportedKeyStoreTypes() {
});
}

/**
* @return Java KeyStore backed truststore types supported by this CryptoProvider for generated truststores.
*/
default Stream<TruststoreFormat> getSupportedTrustStoreTypes() {
Comment thread
slaskawi marked this conversation as resolved.
Resolved
return Stream.of(TruststoreFormat.values())
.filter(TruststoreFormat::isJavaTrustStore)
.filter(format -> supportsTrustStore(this, format));
}

/**
* @return Preferred format for a generated system truststore.
*/
default TruststoreFormat getPreferredGeneratedTrustStoreType() {
if (supportsTrustStore(this, TruststoreFormat.PKCS12)) {
return TruststoreFormat.PKCS12;
}
if (supportsTrustStore(this, TruststoreFormat.BCFKS)) {
return TruststoreFormat.BCFKS;
}
throw new IllegalStateException("No generated Java KeyStore backed truststore types are supported");
}
Comment thread
shawkins marked this conversation as resolved.
Resolved

static boolean supportsTrustStore(CryptoProvider provider, TruststoreFormat format) {
try {
provider.getTrustStore(format);
return true;
} catch (KeyStoreException | NoSuchProviderException ex) {
return false;
}
}

CertificateFactory getX509CertFactory() throws CertificateException, NoSuchProviderException;

CertStore getCertStore(CollectionCertStoreParameters collectionCertStoreParameters) throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, NoSuchProviderException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ public List<String> getFileExtensions() {
public String getPrimaryExtension() {
return fileExtensions.get(0);
}

public boolean isJavaTrustStore() {
return this != PEM;
}
}

public enum KeystoreFormat implements StoreFormat {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ public void testKeystoreFormats() {
KeystoreUtil.KeystoreFormat.BCFKS));
}

@Test
public void testTruststoreFormats() {
Set<KeystoreUtil.TruststoreFormat> supportedTruststoreFormats = CryptoIntegration.getProvider().getSupportedTrustStoreTypes().collect(Collectors.toSet());
assertThat(supportedTruststoreFormats, Matchers.containsInAnyOrder(
KeystoreUtil.TruststoreFormat.JKS,
KeystoreUtil.TruststoreFormat.PKCS12,
KeystoreUtil.TruststoreFormat.BCFKS));
Assert.assertEquals(KeystoreUtil.TruststoreFormat.PKCS12, CryptoIntegration.getProvider().getPreferredGeneratedTrustStoreType());
}

@Test
public void testDefaultKeystoreType() {
Assert.assertEquals("PKCS12", KeystoreUtil.getKeystoreType("PKCS12", "some/foo.jks", "JKS"));
Expand Down
8BD0
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,14 @@ public void testKeystoreFormats() {
KeystoreUtil.KeystoreFormat.PKCS12
));
}

@Test
public void testTruststoreFormats() {
Set<KeystoreUtil.TruststoreFormat> supportedTruststoreFormats = CryptoIntegration.getProvider().getSupportedTrustStoreTypes().collect(Collectors.toSet());
Assert.assertThat(supportedTruststoreFormats, Matchers.containsInAnyOrder(
KeystoreUtil.TruststoreFormat.JKS,
KeystoreUtil.TruststoreFormat.PKCS12
));
Assert.assertEquals(KeystoreUtil.TruststoreFormat.PKCS12, CryptoIntegration.getProvider().getPreferredGeneratedTrustStoreType());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,16 @@ public void testKeystoreFormatsInNonApprovedMode() {
KeystoreUtil.KeystoreFormat.BCFKS));
}

@Test
public void testTruststoreFormatsInNonApprovedMode() {
Assume.assumeFalse(CryptoServicesRegistrar.isInApprovedOnlyMode());
Set<KeystoreUtil.TruststoreFormat> supportedTruststoreFormats = CryptoIntegration.getProvider().getSupportedTrustStoreTypes().collect(Collectors.toSet());
assertThat(supportedTruststoreFormats, Matchers.containsInAnyOrder(
KeystoreUtil.TruststoreFormat.PKCS12,
KeystoreUtil.TruststoreFormat.BCFKS));
assertThat(CryptoIntegration.getProvider().getPreferredGeneratedTrustStoreType(), Matchers.equalTo(KeystoreUtil.TruststoreFormat.PKCS12));
}

// BCFIPS approved mode supports only BCFKS. No JKS nor PKCS12 support for keystores
@Test
public void testKeystoreFormatsInApprovedMode() {
Expand All @@ -48,4 +58,13 @@ public void testKeystoreFormatsInApprovedMode() {
assertThat(supportedKeystoreFormats, Matchers.containsInAnyOrder(
KeystoreUtil.KeystoreFormat.BCFKS));
}

@Test
public void testTruststoreFormatsInApprovedMode() {
Assume.assumeTrue(CryptoServicesRegistrar.isInApprovedOnlyMode());
Set<KeystoreUtil.TruststoreFormat> supportedTruststoreFormats = CryptoIntegration.getProvider().getSupportedTrustStoreTypes().collect(Collectors.toSet());
assertThat(supportedTruststoreFormats, Matchers.containsInAnyOrder(
KeystoreUtil.TruststoreFormat.BCFKS));
assertThat(CryptoIntegration.getProvider().getPreferredGeneratedTrustStoreType(), Matchers.equalTo(KeystoreUtil.TruststoreFormat.BCFKS));
}
}
8 changes: 8 additions & 0 deletions docs/documentation/release_notes/topics/26_7_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,14 @@ Read more about it in the link:https://www.keycloak.org/server/db#multiple-datas

= Configuring and Running

== Generated system truststore uses BCFKS in strict FIPS mode

When {project_name} creates the generated system truststore from `conf/truststores` or `--truststore-paths`, it now selects a store type supported by the active crypto provider.
Default and non-strict FIPS deployments continue to generate a PKCS12 truststore when supported.
Comment thread
slaskawi marked this conversation as resolved.
Resolved
Strict FIPS deployments now generate a BCFKS truststore so the generated truststore can be loaded by the BCFIPS provider in approved mode.

For more details, see the link:{upgradingguide_link}[{upgradingguide_name}].

== Enhanced reverse proxy guides with blueprints for HAProxy and Traefik
// https://github.com/keycloak/keycloak/issues/48002

Expand Down
10 changes: 10 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-26_7_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,16 @@ For the details, see the link:{adminguide_link}[{adminguide_name}].

For all database connections, {project_name} now sets a socket read timeout matching the respective transaction timeout to prevent long hanging threads. For PostgreSQL databases, it additionally sets a query timeout.

=== Generated system truststore format follows the active crypto provider

The generated system truststore created from `conf/truststores`, `--truststore-paths`, and automatically discovered Kubernetes or OpenShift CA certificates now uses the generated truststore format preferred by the active crypto provider.

For most deployments, no configuration change is needed. Non-FIPS and FIPS non-strict mode continue to generate a PKCS12 truststore when PKCS12 is supported.

In strict FIPS mode, the generated system truststore now uses BCFKS instead of PKCS12. If you have automation that reads the generated truststore file directly from the `data` directory, update it to expect `keycloak-truststore.bcfks` with truststore type `BCFKS` instead of `keycloak-truststore.p12` with truststore type `PKCS12`.

This change only affects the generated system truststore. Explicit truststore files configured with options such as `--https-trust-store-file` still use their configured type or the type detected from the file extension.

=== Configure TOTP and Update password required actions moved after Verify Email

In relation to the previous point, the required actions *Configure OTP* and *Update password* have been reordered to appear after *Verify Email*.
Expand Down
2 changes: 2 additions & 0 deletions docs/guides/server/keycloak-truststore.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ If you need an alternative path, use the `--truststore-paths` option to specify

After all applicable certs are included, the truststore will be used as the system default truststore via the `javax.net.ssl` properties, and as the default for internal usage within {project_name}.

The generated system truststore type is automatically adjusted to the current FIPS mode and the active crypto provider. By default, and in FIPS non-strict mode, the generated truststore remains PKCS12 when PKCS12 is supported. In FIPS strict mode, the generated truststore uses BCFKS. The `--https-trust-store-type` option applies to an explicit `--https-trust-store-file`; it does not override the generated system truststore type.

For example:

<@kc.start parameters="--truststore-paths=/opt/truststore/myTrustStore.pfx,/opt/other-truststore/myOtherTrustStore.pem" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,7 @@ void configureManagementInterface(BuildProducer<RouteBuildItem> routes,
@Consume(ConfigBuildItem.class)
@Consume(CryptoProviderInitBuildItem.class) // ensures the Providers are loaded prior to handle the keystore #49359
void configureTruststore(KeycloakRecorder recorder) {
recorder.configureTruststore();
recorder.configureTruststore(getFipsMode());
}

/**
Expand Down Expand Up @@ -911,6 +911,10 @@ public List<HandlerChainCustomizer> scan(MethodInfo method, ClassInfo actualEndp
@BuildStep
@Record(ExecutionTime.STATIC_INIT)
void setCryptoProvider(KeycloakRecorder recorder) {
recorder.setCryptoProvider(getFipsMode());
}

private FipsMode getFipsMode() {
FipsMode fipsMode = getOptionalValue(NS_KEYCLOAK_PREFIX + SecurityOptions.FIPS_MODE.getKey())
.map(FipsMode::valueOfOption)
.orElse(FipsMode.DISABLED);
Expand All @@ -920,8 +924,7 @@ void setCryptoProvider(KeycloakRecorder recorder) {
} else if (fipsMode.isFipsEnabled() && !Profile.isFeatureEnabled(Profile.Feature.FIPS)) {
throw new RuntimeException("FIPS mode cannot be enabled without enabling the FIPS feature --features=fips");
}

recorder.setCryptoProvider(fipsMode);
return fipsMode;
}

@BuildStep(>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.keycloak.common.crypto.CryptoIntegration;
import org.keycloak.common.crypto.CryptoProvider;
import org.keycloak.common.crypto.FipsMode;
import org.keycloak.common.util.KeystoreUtil.TruststoreFormat;
import org.keycloak.config.DatabaseOptions;
import org.keycloak.config.HealthOptions;
import org.keycloak.config.HttpAccessLogOptions;
Expand Down Expand Up @@ -130,7 +131,7 @@ public Handler<RoutingContext> getRejectNonNormalizedPathFilter() {
return !Configuration.isTrue(HttpOptions.HTTP_ACCEPT_NON_NORMALIZED_PATHS) ? new RejectNonNormalizedPathFilter() : null;
}

public void configureTruststore() {
public void 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 @@ -151,7 +152,9 @@ public void configureTruststore() {
return; // nothing to configure, we'll just use the system default
}

TruststoreBuilder.setSystemTruststore(truststores.toArray(String[]::new), true, dataDir.orElseThrow());
TruststoreFormat truststoreType = fipsMode == FipsMode.STRICT ? TruststoreFormat.BCFKS : null;

TruststoreBuilder.setSystemTruststore(truststores.toArray(String[]::new), true, dataDir.orElseThrow(), truststoreType);
}

public void configureLiquibase(Map<String, List<String>> services) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.keycloak.it.cli.dist;

import java.nio.file.Files;
import java.nio.file.Path;

import org.keycloak.it.junit5.extension.CLIResult;
Expand All @@ -29,6 +30,9 @@
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* Reproduces <a href="https://github.com/keycloak/keycloak/issues/49139">#49139</a>:
* When FIPS is enabled with truststore configuration, the configureTruststore build
Expand Down Expand Up @@ -95,6 +99,21 @@ void testBcFipsBundledWithoutFipsFeatureFailsOnCryptoProvider(KeycloakRunner run
cliResult.assertError("Unexpected error when configuring the crypto provider");
}

@Test
void testGeneratedTruststoreUsesBcfksInStrictMode(KeycloakRunner runner) {
RawKeycloakDistribution rawDist = runner.getDistribution(RawKeycloakDistribution.class);
installBcFips(rawDist);

rawDist.copyOrReplaceFileFromClasspath("/self-signed.pem", Path.of("conf", "truststores", "self-signed.pem"));

CLIResult cliResult = runner.run("--verbose", "start", "--features=fips", "--fips-mode=strict");
cliResult.assertStarted();
cliResult.assertMessage("FIPS1402Provider created");

assertTrue(Files.exists(rawDist.getDistPath().resolve("data").resolve("keycloak-truststore.bcfks")));
assertFalse(Files.exists(rawDist.getDistPath().resolve("data").resolve("keycloak-truststore.p12")));
}

private void installBcFips(RawKeycloakDistribution rawDist) {
rawDist.copyProvider("org.bouncycastle", "bc-fips");
rawDist.copyProvider("org.bouncycastle", "bctls-fips");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.keycloak.it.cli.dist;

import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand All @@ -35,6 +36,8 @@
import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

@DistributionTest(stopServer = Mode.MANUAL)
@RawDistOnly(reason = "Containers are immutable")
Expand Down Expand Up @@ -81,6 +84,9 @@ void testMutualAuthWithDefaultTruststoresDir(KeycloakRunner runner) {
runner.run("--verbose", "start", "--db=dev-file", "--http-enabled=true", "--hostname=mykeycloak.org",
"--https-client-auth=required", "--https-key-store-file=" + keyStore);

assertTrue(Files.exists(rawDist.getDistPath().resolve("data").resolve("keycloak-truststore.p12")));
assertFalse(Files.exists(rawDist.getDistPath().resolve("data").resolve("keycloak-truststore.bcfks")));

given().trustStore(TruststoreDistTest.class.getResource("/self-signed-truststore.p12").getPath(), TruststoreBuilder.DUMMY_PASSWORD)
.keyStore(TruststoreDistTest.class.getResource("/self-signed.p12").getPath(), "password")
.get("https://mykeycloak.org:8443").then().body(Matchers.containsString("https://mykeycloak.org"));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ public void init(Config.Scope config) {
String httpsTrustStoreType = config.root().get(HttpOptions.HTTPS_TRUST_STORE_TYPE.getKey());
final String truststoreType = KeystoreUtil.getTruststoreType(httpsTrustStoreType, httpsTrustStoreFile, KeyStore.getDefaultType());
if (KeystoreUtil.TruststoreFormat.PEM.name().equalsIgnoreCase(truststoreType)) {
httpsTruststore = TruststoreBuilder.createPkcs12KeyStore();
httpsTruststore = TruststoreBuilder.createGeneratedTrustStore();
TruststoreBuilder.mergePemFile(httpsTruststore, httpsTrustStoreFile, true);
} else {
httpsTruststore = KeystoreUtil.loadKeyStore(httpsTrustStoreFile, httpsTrustStorePassword, httpsTrustStoreType);
Expand Down
Loading
Loading
0