8000 Support encrypted PEM TLS certificate key by michalvavrik · Pull Request #51567 · 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
Diff view
6 changes: 6 additions & 0 deletions docs/documentation/release_notes/topics/26_8_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ As part of ongoing secure-by-default improvements to impersonation, token lifecy

Additionally, tokens issued from impersonation sessions now include the `act` (actor) claim (https://datatracker.ietf.org/doc/html/rfc8693#section-4.1[RFC 8693 Section 4.1]) in both access tokens and ID tokens. This allows downstream resource servers to identify the impersonator for audit purposes. The claim is always present and cannot be disabled.

= Configuring and Running

== Support for encrypted PEM private keys

{project_name} now supports encrypted PKCS#8 private keys in PEM format for HTTPS configuration. Use the new `--https-certificate-key-file-password` option to provide the decryption password. The management interface also supports this via `--https-management-certificate-key-file-password`. For details, see <@links.server id="enabletls"/>.

= Themes

== Redesigned identity provider buttons on the login page
Expand Down
31 changes: 25 additions & 6 deletions docs/guides/server/enabletls.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,27 @@ When you use a pair of matching certificate and private key files in PEM format,

<@kc.start parameters="--https-certificate-file=/path/to/certfile.pem --https-certificate-key-file=/path/to/keyfile.pem"/>

{project_name} creates a keystore out of these files in memory and uses this keystore afterwards.
=== Using encrypted private keys
If your PEM private key is encrypted (PKCS#8 encrypted format), provide the decryption password using the `https-certificate-key-file-password` option:

<@kc.start parameters="--https-certificate-file=/path/to/certfile.pem --https-certificate-key-file=/path/to/encrypted-keyfile.pem --https-certificate-key-file-password=<password>"/>

To create an encrypted private key with OpenSSL:

----
openssl genpkey -algorithm RSA -out keyfile.pem -aes-256-cbc
----

Or to convert an existing unencrypted key:

----
openssl pkcs8 -topk8 -in unencrypted.pem -out encrypted.pem -v2 aes-256-cbc
----

Avoid setting the password directly on the command line or adding it to the `conf/keycloak.conf` file.
Instead use good practices such as using a vault / mounted secret, or the `KC_HTTPS_CERTIFICATE_KEY_FILE_PASSWORD` environment variable. For more detail, see <@links.server id="vault"/> and <@links.server id="configuration-production" />.

The management interface also supports this via `https-management-certificate-key-file-password`.

== Providing a Keystore
When no keystore file is explicitly configured, but `http-enabled` is set to false, {project_name} looks for a `conf/server.keystore` file.
Expand All @@ -29,11 +49,10 @@ As an alternative, you can use an existing keystore by running the following com

Recognized file extensions for a keystore:

* `.p12`, `.pkcs12`, and `.pfx` for a pkcs12 file
* `.jks`, and `.keystore` for a jks file
* `.key`, `.crt`, and `.pem` for a pem file
* `.p12`, `.pkcs12`, and `.pfx` for a PKCS12 file
* `.jks` and `.keystore` for a JKS file

If your keystore does not have an extension matching its file type, you will also need to set the `https-key-store-type` option.
If your keystore does not have one of these extensions, you must set the `https-key-store-type` option. For BCFKS keystores (used in FIPS mode), the type is set automatically when `--fips-mode=strict` is enabled. Similarly, `.truststore` is recognized for JKS trust stores.

=== Setting the Keystore password
You can set a secure password for your keystore using the `https-key-store-password` option:
Expand All @@ -42,7 +61,7 @@ You can set a secure password for your keystore using the `https-key-store-passw
If no password is set, the default password `password` is used.

==== Securing credentials
Avoid setting a password in plaintext by using the CLI or adding it to `conf/keycloak.conf` file.
Avoid setting the password directly on the command line or adding it to the `conf/keycloak.conf` file.
Instead use good practices such as using a vault / mounted secret. For more detail, see <@links.server id="vault"/> and <@links.server id="configuration-production" />.

== Configuring TLS protocols
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,11 @@ public enum ClientAuth {
.description("The file path to a private key in PEM format.")
.build();

public static final Option<String> HTTPS_CERTIFICATE_KEY_FILE_PASSWORD = new OptionBuilder<>("https-certificate-key-file-password", String.class)
.category(OptionCategory.HTTP)
.description("The password to decrypt an encrypted private key in PEM format (encrypted PKCS#8).")
.build();

public static final Option<File> HTTPS_KEY_STORE_FILE = new OptionBuilder<>("https-key-store-file", File.class)
.category(OptionCategory.HTTP)
.description("The key store which holds the certificate information instead of specifying separate files.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,11 @@ public enum Scheme {
.description("The file path to a private key in PEM format for the management server. If not given, the value is inherited from HTTP options. " + RELEVANT_MSG)
.build();

public static final Option<String> HTTPS_MANAGEMENT_CERTIFICATE_KEY_FILE_PASSWORD = new OptionBuilder<>("https-management-certificate-key-file-password", String.class)
.category(OptionCategory.MANAGEMENT)
.description("The password to decrypt an encrypted private key in PEM format for the management server. If not given, the value is inherited from HTTP options. " + RELEVANT_MSG)
.build();

public static final Option<File> HTTPS_MANAGEMENT_KEY_STORE_FILE = new OptionBuilder<>("https-management-key-store-file", File.class)
.category(OptionCategory.MANAGEMENT)
.description("The key store which holds the certificate information instead of specifying separate files for the management server. If not given, the value is inherited from HTTP options. " + RELEVANT_MSG)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ public static void reset(Properties systemProperties) {
PersistedConfigSource.getInstance().getConfigValueProperties().clear();
Profile.reset();
Configuration.resetConfig();
ExecutionExceptionHandler.resetExceptionTransformers();
}

public static void main(String[] args, Picocli picocli) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ public void rejectNonNormalizedPathFilter(RuntimeValue<Router> runtimeValue) {

public void misdirectedRequestFilter(RuntimeValue<Router> runtimeValue) {
// not checking for http/2 enablement - it is enabled by default and not exposed as a supported configuration option
if (!Configuration.isTrue(HttpPropertyMappers.QUARKUS_HTTPS_SNI) || !HttpPropertyMappers.isHttpsEnabled() || Configuration.getConfigValue(ProxyOptions.PROXY_HEADERS).getValue() != null) {
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Configuration.isTrue(HttpPropertyMappers.QUARKUS_HTTPS_SNI) was initially part of this check because our sni option was going to be hidden, not synthetic. It's fine to remove it and we can revisit this if / when we want to give users control over whether SNI is enabled. Or if the mapping to QUARKUS_HTTPS_SNI is added back, then I'd also restore this check.

if (!HttpPropertyMappers.isHttpsEnabled() || Configuration.getConfigValue(ProxyOptions.PROXY_HEADERS).getValue() != null) {
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,34 +18,24 @@
package org.keycloak.quarkus.runtime.cli;

import java.io.PrintWriter;
import java.nio.file.FileSystemException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

import org.keycloak.quarkus.runtime.Environment;
import org.keycloak.quarkus.runtime.Messages;

import io.quarkus.bootstrap.logging.InitialConfigurator;
import io.smallrye.config.ConfigValue;
import org.jboss.logging.Logger;
import picocli.CommandLine;
import picocli.CommandLine.ParseResult;

import static org.keycloak.quarkus.runtime.configuration.Configuration.getConfig;

public final class ExecutionExceptionHandler implements CommandLine.IExecutionExceptionHandler {

private static Logger logger;
private boolean verbose;
private static Map<String, Function<Throwable, Throwable>> exceptionTransformers = new HashMap<>();

public ExecutionExceptionHandler() {}

@Override
public int handleExecutionException(Exception cause, CommandLine cmd, ParseResult parseResult) {
var exception = handleExceptionTransformers(cause);
var exception = cause;
Comment thread
michalvavrik marked this conversation as resolved.
Resolved
if (exception instanceof PropertyException) {
PrintWriter writer = cmd.getErr();
writer.println(cmd.getColorScheme().errorText(exception.getMessage()));
Expand All @@ -63,13 +53,12 @@ public int handleExecutionException(Exception cause, CommandLine cmd, ParseResul
}

public void error(PrintWriter errorWriter, String message, Throwable cause) {
var exception = handleExceptionTransformers(cause);
if (message != null) {
logError(errorWriter, "ERROR: " + message);
}

if (exception != null) {
dumpException(errorWriter, exception);
if (cause != null) {
dumpException(errorWriter, cause);

if (!verbose) {
logError(errorWriter, "For more details run the same command passing the '--verbose' option. Also you can use '--help' to see the details about the usage of the particular command.");
Expand All @@ -85,22 +74,8 @@ private void dumpException(PrintWriter errorWriter, Throwable cause) {
if (cause.getMessage() != null) {
logError(errorWriter, String.format("ERROR: %s", cause.getMessage()));
}
printErrorHints(errorWriter, cause);
} while ((cause = cause.getCause()) != null);
}

printErrorHints(errorWriter, cause);
}

private void printErrorHints(PrintWriter errorWriter, Throwable cause) {
if (cause instanceof FileSystemException) {
FileSystemException fse = (FileSystemException) cause;
ConfigValue httpsCertFile = getConfig().getConfigValue("kc.https-certificate-file");

if (fse.getFile().equals(Optional.ofNullable(httpsCertFile.getValue()).orElse(null))) {
logError(errorWriter, Messages.httpsConfigurationNotSet());
}
}
}

private void logError(PrintWriter errorWriter, String errorMessage) {
Expand Down Expand Up @@ -137,33 +112,4 @@ public void setVerbose(boolean verbose) {
this.verbose = verbose;
}

public static void addExceptionTransformer(Class<?> fromClass, Function<Throwable, Throwable> transformer) {
if (exceptionTransformers.get(fromClass.getName()) != null) {
getLogger().warnf("Transformer for the '%s' class is overridden", fromClass.getName());
}
exceptionTransformers.put(fromClass.getName(), transformer);
}

public static void resetExceptionTransformers() {
exceptionTransformers = new HashMap<>();
}

private static Throwable handleExceptionTransformers(Throwable exception) {
if (exception == null) {
return null;
}

if (exceptionTransformers.isEmpty()) {
return exception;
}

var stackTrace = exception.getStackTrace();
for (var trace : stackTrace) {
var transformer = exceptionTransformers.get(trace.getClassName());
if (transformer != null) {
return transformer.apply(exception);
}
}
return exception;
}
}
Loading
Loading
0