8000 Trust managed TLS certificates for outbound connections by trixpan · Pull Request #54143 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Open
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
Diff view
4 changes: 4 additions & 0 deletions .github/scripts/run-fips-it.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ TESTSUITE_NAME="FipsNonStrictTestSuite"
if [ "$1" = "strict" ]; then
STRICT_OPTIONS="-Dauth.server.fips.mode=strict -Dauth.server.supported.keystore.types=BCFKS -Dauth.server.keystore.type=bcfks -Dauth.server.supported.rsa.key.sizes=2048,3072,4096"
TESTSUITE_NAME="FipsStrictTestSuite"
else
# RH OpenJDK ships cacerts as JKS, but merging the default truststore assumes PKCS12, which BCFIPS rejects in non-strict mode
# Remove once https://github.com/keycloak/keycloak/issues/28526 is fixed
export JAVA_OPTS_APPEND="-Djavax.net.ssl.trustStore=/etc/alternatives/java_sdk_${JAVA_VERSION}/lib/security/cacerts -Djavax.net.ssl.trustStoreType=JKS -Djavax.net.ssl.trustStorePassword=changeit"
fi
echo "STRICT_OPTIONS: $STRICT_OPTIONS"
TESTS=`testsuite/integration-arquillian/tests/base/testsuites/suite.sh fips`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,27 @@
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.HexFormat;
import javax.net.ssl.SSLContext;

import org.keycloak.common.crypto.CryptoIntegration;
import org.keycloak.common.crypto.CryptoProvider;
import org.keycloak.common.util.KeystoreUtil;
import org.keycloak.common.util.PemUtils;
import org.keycloak.crypto.def.DefaultCryptoProvider;

import org.apache.http.conn.ssl.TrustAllStrategy;
Expand Down Expand Up @@ -48,6 +54,7 @@ public class ManagedCertificates {
private KeyStore clientKeyStore;

private final Path clientTruststorePath;
private final Path clientTruststorePemPath;
private KeyStore clientTrustStore;

private final SSLContext clientSslContext;
Expand Down Expand Up @@ -83,12 +90,14 @@ public ManagedCertificates(CertificatesConfigBuilder configBuilder) throws Manag
clientKeyStore = load(clientKeystorePath);
clientTrustStore = load(clientTruststorePath);
}
clientTruststorePemPath = saveAsPem(clientTrustStore);
clientSslContext = createClientSSLContext();
} else {
serverKeystorePath = null;
serverTruststorePath = null;
clientKeystorePath = null;
clientTruststorePath = null;
clientTruststorePemPath = null;
clientSslContext = null;
}
}
Expand Down Expand Up @@ -128,6 +137,16 @@ public String getServerTrustStorePassword() {
return mTlsEnabled ? STORE_PASSWORD : null;
}

/**
* The path of a PEM bundle containing certificates trusted by managed clients. The server uses the same bundle
* for outbound TLS connections.
*
* @return path to PEM trust bundle
*/
public String getClientTrustStorePath() {
return tlsEnabled ? clientTruststorePemPath.toString() : null;
}

/**
* Return the SSL context configured with the client truststore
*
Expand Down Expand Up @@ -260,6 +279,26 @@ private Path resolvePath(String fileName) {
return KEYSTORES_DIR.resolve(fileName + "." + keystoreFormat.getPrimaryExtension());
}

private Path saveAsPem(KeyStore trustStore) {
try {
StringBuilder pem = new StringBuilder();
for (String alias : Collections.list(trustStore.aliases())) {
Certificate certificate = trustStore.getCertificate(alias);
if (certificate != null) {
pem.append(PemUtils.addCertificateBeginEnd(PemUtils.encodeCertificate(certificate))).append('\n');
}
}

byte[] trustMaterial = pem.toString().getBytes(StandardCharsets.UTF_8);
String trustMaterialHash = HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(trustMaterial));
Path trustStorePath = KEYSTORES_DIR.resolve("kc-testing-client-truststore-" + trustMaterialHash + ".pem");
Files.write(trustStorePath, trustMaterial);
return trustStorePath;
} catch (Exception e) {
throw new ManagedCertificatesException(e);
}
}

private void save(KeyStore store, Path storePath) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException {
try (FileOutputStream fos = new FileOutputStream(storePath.toFile())) {
store.store(fos, STORE_PASSWORD_CHARS);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,15 @@ public KeycloakServer getValue(InstanceContext<KeycloakServer, KeycloakIntegrati
command.option("https-key-store-file", managedCert.getServerKeyStorePath());
command.option("https-key-store-password", managedCert.getServerKeyStorePassword());
command.option("https-key-store-type", managedCert.getKeystoreFormat().name());
command.addOption("truststore-paths", managedCert.getClientTrustStorePath());
}

if (managedCert.isMTlsEnabled()) {
command.option("https-client-auth", "request");
if (KeystoreUtil.TruststoreFormat.PEM.name().equalsIgnoreCase(KeystoreUtil.getTruststoreType(
null, managedCert.getServerTrustStorePath(), managedCert.getKeystoreFormat().name()))) {
// for PEM file use common truststore paths option
command.option("truststore-paths", managedCert.getServerTrustStorePath());
command.addOption("truststore-paths", managedCert.getServerTrustStorePath());
} else {
// for other formats use the https-trust-store-file option
command.option("https-trust-store-file", managedCert.getServerTrustStorePath());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,11 @@ private DistributionKeycloakServer.OutputHandler startKeycloak(List<String> args
List<String> cmd = new LinkedList<>();
if (Environment.isWindows()) {
cmd.add(keycloakHomeDir.toPath().resolve("bin").resolve(CMD).toString());
args.stream().map(DistributionKeycloakServer::quoteWindowsBatchArgument).forEach(cmd::add);
} else {
cmd.add("./" + CMD);
cmd.addAll(args);
}
cmd.addAll(args);

ProcessBuilder pb = new ProcessBuilder(cmd);
pb.directory(new File(keycloakHomeDir, "bin"));
Expand Down Expand Up @@ -199,6 +200,12 @@ private DistributionKeycloakServer.OutputHandler startKeycloak(List<String> args
return outputHandler;
}

// cmd.exe splits unquoted batch file arguments on commas, which breaks list values such as --features=a,b.
// kc.bat passes the quoted argument on to java, which removes the quotes again.
static String quoteWindowsBatchArgument(String argument) {
return argument.indexOf(',') >= 0 ? '"' + argument + '"' : argument;
}

@Override
public void stop() {
if (!reuse) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,18 @@ public KeycloakServerConfigBuilder option(String key, String value) {
return this;
}

/**
* Add another value to a list-valued CLI option without replacing values already configured
*
* @param key the key of the option
* @param value the additional value to set
* @return
*/
public KeycloakServerConfigBuilder addOption(String key, String value) {
options.merge(key, value, (current, additional) -> current + "," + additional);
return this;
}

/**
* Set an SPI configuration option
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.keycloak.testframework.server;

import java.util.List;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class KeycloakServerConfigBuilderTest {

@Test
public void addOptionCombinesListValues() {
KeycloakServerConfigBuilder builder = KeycloakServerConfigBuilder.startDev()
.option("truststore-paths", "custom.pem")
.addOption("truststore-paths", "managed.pem");

List<String> args = builder.toArgs();
Assertions.assertEquals(1, args.stream().filter(a -> a.startsWith("--truststore-paths=")).count());
Assertions.assertTrue(args.contains("--truststore-paths=custom.pem,managed.pem"));
}

@Test
public void quoteWindowsBatchArgument() {
Assertions.assertEquals("\"--truststore-paths=C:\\custom.pem,C:\\managed.pem\"",
DistributionKeycloakServer.quoteWindowsBatchArgument("--truststore-paths=C:\\custom.pem,C:\\managed.pem"));
Assertions.assertEquals("--http-enabled=true", DistributionKeycloakServer.quoteWindowsBatchArgument("--http-enabled=true"));
}
}
< C7DD /tr>
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
package org.keycloak.testframework.tests;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.cert.X509Certificate;

import org.keycloak.admin.client.Keycloak;
import org.keycloak.common.crypto.CryptoIntegration;
import org.keycloak.common.util.CertificateUtils;
import org.keycloak.common.util.KeyUtils;
import org.keycloak.common.util.PemUtils;
import org.keycloak.connections.httpclient.HttpClientProvider;
import org.keycloak.crypto.def.DefaultCryptoProvider;
import org.keycloak.testframework.annotations.InjectAdminClient;
import org.keycloak.testframework.annotations.InjectHttpClient;
import org.keycloak.testframework.annotations.InjectKeycloakUrls;
Expand All @@ -14,6 +27,10 @@
import org.keycloak.testframework.https.ManagedCertificates;
import org.keycloak.testframework.oauth.OAuthClient;
import org.keycloak.testframework.oauth.annotations.InjectOAuthClient;
import org.keycloak.testframework.remote.runonserver.InjectRunOnServer;
import org.keycloak.testframework.remote.runonserver.RunOnServerClient;
import org.keycloak.testframework.server.KeycloakServerConfig;
import org.keycloak.testframework.server.KeycloakServerConfigBuilder;
import org.keycloak.testframework.server.KeycloakUrls;

import org.apache.http.HttpResponse;
Expand All @@ -22,7 +39,7 @@
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

@KeycloakIntegrationTest
@KeycloakIntegrationTest(config = TlsEnabledTest.TlsServerConfig.class)
public class TlsEnabledTest {

@InjectHttpClient
Expand All @@ -40,12 +57,16 @@ public class TlsEnabledTest {
@InjectKeycloakUrls
KeycloakUrls keycloakUrls;

@InjectRunOnServer
RunOnServerClient runOnServer;

@Test
public void testCertSupplier() {
Assertions.assertNotNull(managedCertificates);

Assertions.assertNotNull(managedCertificates.getServerKeyStorePath());
Assertions.assertNull(managedCertificates.getServerTrustStorePath());
Assertions.assertNotNull(managedCertificates.getClientTrustStorePath());

Assertions.assertNotNull(managedCertificates.getClientSSLContext());
}
Expand All @@ -70,6 +91,64 @@ public void testOAuthClient() {
Assertions.assertTrue(oAuthClient.doWellKnownRequest().getTokenEndpoint().startsWith("https://"));
}

@Test
public void testServerHttpClient() {
String url = keycloakUrls.getMasterRealm() + "/.well-known/openid-configuration";
String response = runOnServer.fetchString(session -> session.getProvider(HttpClientProvider.class).getString(url));
Assertions.assertTrue(response.contains("\"issuer\":\"" + keycloakUrls.getMasterRealm() + "\""));
}

@Test
public void testServerTruststore() throws IOException {
String expected = PemUtils.addCertificateBeginEnd(TlsServerConfig.CUSTOM_CERTIFICATE)
+ Files.readString(Path.of(managedCertificates.getClientTrustStorePath()));
String trusted = runOnServer.fetchString(session -> {
try (InputStream is = new FileInputStream(System.getProperty("javax.net.ssl.trustStore"))) {
KeyStore truststore = KeyStore.getInstance(System.getProperty("javax.net.ssl.trustStoreType"));
truststore.load(is, System.getProperty("javax.net.ssl.trustStorePassword").toCharArray());
for (X509Certificate certificate : PemUtils.decodeCertificates(expected)) {
if (truststore.getCertificateAlias(certificate) == null) {
return "false";
}
}
return "true";
} catch (Exception e) {
throw new RuntimeException(e);
}
});
Assertions.assertEquals("true", trusted);
}

public static class TlsServerConfig implements KeycloakServerConfig {

// a certificate configured by the test itself must be trusted alongside the managed certificate
static final String CUSTOM_CERTIFICATE = generateCertificate();
private static final Path CUSTOM_TRUSTSTORE = writeTruststore(CUSTOM_CERTIFICATE);

@Override
public KeycloakServerConfigBuilder configure(KeycloakServerConfigBuilder config) {
return config.option("truststore-paths", CUSTOM_TRUSTSTORE.toString());
}

private static String generateCertificate() {
if (!CryptoIntegration.isInitialised()) {
CryptoIntegration.setProvider(new DefaultCryptoProvider());
}
KeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);
return PemUtils.encodeCertificate(CertificateUtils.generateV1SelfSignedCertificate(keyPair, "custom-truststore"));
}

private static Path writeTruststore(String certificate) {
try {
Path path = Files.createTempFile("kc-testing-custom-truststore", ".pem");
path.toFile().deleteOnExit();
return Files.writeString(path, PemUtils.addCertificateBeginEnd(certificate));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

private static class TlsEnabledConfig implements CertificatesConfig {

@Override
Expand Down
Loading
0