8000 Raise generated cache-transport RSA keys to 3072 bits and allow ECDSA by ahus1 · Pull Request #55224 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
Draft
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
2 changes: 1 addition & 1 deletion .github/scripts/run-fips-it.sh
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ if [ $? -ne 0 ]; then
fi

# Profile app-server-wildfly needs to be explicitly set for FIPS tests
./mvnw test -Dsurefire.rerunFailingTestsCount=$SUREFIRE_RERUN_FAILING_COUNT -nsu -B -Pauth-server-quarkus,auth-server-fips140-2,app-server-wildfly -Dcom.redhat.fips=false -Dredhat.crypto-policies=false $STRICT_OPTIONS -Dtest=$TESTS -pl testsuite/integration-arquillian/tests/base 2>&1 | misc/log/trimmer.sh
./mvnw test -Dsurefire.rerunFailingTestsCount=$SUREFIRE_RERUN_FAILING_COUNT -nsu -B -Pauth-server-quarkus,auth-server-fips140-2,app-server-wildfly -Dcom.redhat.fips=false -Dredhat.crypto-policies=false -Dauth.server.quarkus.cluster.config=default $STRICT_OPTIONS -Dtest=$TESTS -pl testsuite/integration-arquillian/tests/base 2>&1 | misc/log/trimmer.sh
if [ $? -ne 0 ]; then
exit 1
fi
Expand Down
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -1331,12 +1331,12 @@ jobs:
download-dist: true

- name: Run tests
run: ./mvnw verify -pl tests/clustering
run: ./mvnw verify -pl tests/clustering -Dtest=MixedClusterTestSuite
env:
KC_TEST_SERVER_IMAGES: "quay.io/keycloak/keycloak:${{ matrix.version }},-"

- name: Run tests with stateless
run: ./mvnw verify -pl tests/clustering -Dsurefire.reportNameSuffix=stateless
run: ./mvnw verify -pl tests/clustering -Dtest=MixedClusterTestSuite -Dsurefire.reportNameSuffix=stateless
env:
KC_TEST_SERVER_IMAGES: "quay.io/keycloak/keycloak:${{ matrix.version }},-"
KC_TEST_SERVER_STATELESS: "true"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,11 @@ public X509Certificate generateV3Certificate(KeyPair keyPair, PrivateKey caPriva

public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber, Date validityEndDate);

/**
* @param rsaPss sign RSA keys with RSASSA-PSS instead of PKCS #1 v1.5; ignored for other key types
*/
public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber, Date validityEndDate, boolean rsaPss);

public List<String> getCertificatePolicyList(X509Certificate cert) throws GeneralSecurityException;

public List<String> getCRLDistributionPoints(X509Certificate cert) throws IOException;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,13 @@ public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair,
return CryptoIntegration.getProvider().getCertificateUtils().generateV1SelfSignedCertificate(caKeyPair, truncateCN(subject), serialNumber, validityEndDate);
}

/**
* @param rsaPss sign RSA keys with RSASSA-PSS instead of PKCS #1 v1.5; ignored for other key types
*/
public static X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber, Date validityEndDate, boolean rsaPss) {
return CryptoIntegration.getProvider().getCertificateUtils().generateV1SelfSignedCertificate(caKeyPair, truncateCN(subject), serialNumber, validityEndDate, rsaPss);
}

/**
* Checks whether the certificate is self signed, meaning it is self issued with matching subject and
* issuer names and its signature verifies with its own public key.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -171,14 +171,19 @@ public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String

@Override
public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber, Date validityEndDate) {
return generateV1SelfSignedCertificate(caKeyPair, subject, serialNumber, validityEndDate, false);
}

@Override
public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber, Date validityEndDate, boolean rsaPss) {
try {
X500Name subjectDN = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, subject).build();
Date validityStartDate = new Date(System.currentTimeMillis() - 100000);
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded());

X509v1CertificateBuilder builder = new X509v1CertificateBuilder(subjectDN, serialNumber, validityStartDate,
validityEndDate, subjectDN, subPubKeyInfo);
X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate()));
X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate(), rsaPss));

return new JcaX509CertificateConverter().getCertificate(holder);
} catch (Exception e) {
Expand All @@ -190,14 +195,15 @@ public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String
* Creates the content signer for generation of Version 1 {@link X509Certificate}.
*
* @param privateKey the private key
* @param rsaPss use RSASSA-PSS instead of PKCS #1 v1.5 for RSA keys
* @return the content signer
*/
private ContentSigner createSigner(PrivateKey privateKey) {
private ContentSigner createSigner(PrivateKey privateKey, boolean rsaPss) {
try {
JcaContentSignerBuilder signerBuilder;
switch (privateKey.getAlgorithm()) {
case "RSA": {
signerBuilder = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
signerBuilder = new JcaContentSignerBuilder(rsaPss ? "SHA256WITHRSAANDMGF1" : "SHA256WithRSAEncryption")
.setProvider(BouncyIntegration.PROVIDER);
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,19 @@ public void testV1SelfSignedCertificateWithSpecialCharactersInSubject() {
Assert.assertEquals(subject, extractCN(certificate));
}

@Test
public void testV1SelfSignedCertificateWithRsaPss() throws Exception {
KeyPair keyPair = KeyUtils.generateRsaKeyPair(2048);
java.util.Date end = new java.util.Date(System.currentTimeMillis() + 100000);

X509Certificate pss = CertificateUtils.generateV1SelfSignedCertificate(keyPair, "pss", java.math.BigInteger.ONE, end, true);
X509Certificate pkcs1 = CertificateUtils.generateV1SelfSignedCertificate(keyPair, "pkcs1", java.math.BigInteger.ONE, end, false);

Assert.assertEquals("1.2.840.113549.1.1.10", pss.getSigAlgOID());
Assert.assertEquals("1.2.840.113549.1.1.11", pkcs1.getSigAlgOID());
pss.verify(keyPair.getPublic());
}

@Test
public void testV3CertificateWithSpecialCharactersInSubject() throws Exception {
String subject = "https://example.com/?action=sso_id";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,11 @@ public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String

@Override
public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber, Date validityEndDate) {
return generateV1SelfSignedCertificate(caKeyPair, subject, serialNumber, validityEndDate, false);
}

@Override
public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber, Date validityEndDate, boolean rsaPss) {
try {

X500Principal subjectdn = cnToX500Principal(subject);
Expand Down Expand Up @@ -202,7 +207,7 @@ public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String
cbuilder.setSignatureAlgorithmName("SHA256withECDSA");
break;
default:
cbuilder.setSignatureAlgorithmName("SHA256withRSA");
cbuilder.setSignatureAlgorithmName(rsaPss ? "RSASSA-PSS" : "SHA256withRSA");
}

return cbuilder.build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,14 +173,19 @@ public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String

@Override
public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber, Date validityEndDate) {
return generateV1SelfSignedCertificate(caKeyPair, subject, serialNumber, validityEndDate, false);
}

@Override
public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String subject, BigInteger serialNumber, Date validityEndDate, boolean rsaPss) {
try {
X500Name subjectDN = new X500NameBuilder(BCStyle.INSTANCE).addRDN(BCStyle.CN, subject).build();
Date validityStartDate = new Date(System.currentTimeMillis() - 100000);
SubjectPublicKeyInfo subPubKeyInfo = SubjectPublicKeyInfo.getInstance(caKeyPair.getPublic().getEncoded());

X509v1CertificateBuilder builder = new X509v1CertificateBuilder(subjectDN, serialNumber, validityStartDate,
validityEndDate, subjectDN, subPubKeyInfo);
X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate()));
X509CertificateHolder holder = builder.build(createSigner(caKeyPair.getPrivate(), rsaPss));

return new JcaX509CertificateConverter().getCertificate(holder);
} catch (Exception e) {
Expand All @@ -192,15 +197,16 @@ public X509Certificate generateV1SelfSignedCertificate(KeyPair caKeyPair, String
* Creates the content signer for generation of Version 1 {@link X509Certificate}.
*
* @param privateKey the private key
* @param rsaPss use RSASSA-PSS instead of PKCS #1 v1.5 for RSA keys
*
* @return the content signer
*/
private ContentSigner createSigner(PrivateKey privateKey) {
private ContentSigner createSigner(PrivateKey privateKey, boolean rsaPss) {
try {
JcaContentSignerBuilder signerBuilder;
switch (privateKey.getAlgorithm()) {
case "RSA": {
signerBuilder = new JcaContentSignerBuilder("SHA256WithRSAEncryption")
signerBuilder = new JcaContentSignerBuilder(rsaPss ? "SHA256WITHRSAANDMGF1" : "SHA256WithRSAEncryption")
.setProvider(BouncyIntegration.PROVIDER);
break;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@ public void testV1SelfSignedCertificateWithSpecialCharactersInSubject() {
Assert.assertEquals(subject, extractCN(certificate));
}

@Test
public void testV1SelfSignedCertificateWithRsaPssAndEcdsa() throws Exception {
java.util.Date end = new java.util.Date(System.currentTimeMillis() + 100000);

KeyPair rsa = KeyUtils.generateRsaKeyPair(3072);
X509Certificate pss = CertificateUtils.generateV1SelfSignedCertificate(rsa, "pss", java.math.BigInteger.ONE, end, true);
Assert.assertEquals("1.2.840.113549.1.1.10", pss.getSigAlgOID());
pss.verify(rsa.getPublic());

KeyPair ec = KeyUtils.generateEcKeyPair("secp256r1");
X509Certificate ecdsa = CertificateUtils.generateV1SelfSignedCertificate(ec, "ec", java.math.BigInteger.ONE, end, true);
ecdsa.verify(ec.getPublic());
}

@Test
public void testV3CertificateWithSpecialCharactersInSubject() throws Exception {
String subject = "https://example.com/?action=sso_id";
Expand Down
8 changes: 8 additions & 0 deletions docs/documentation/release_notes/topics/27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ See the upgrading guide for details.

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.

== Stronger certificate for cache transport between nodes
// https://github.com/keycloak/keycloak/issues/54496

The automatically generated certificate that secures the communication between {project_name} nodes now uses a 3072-bit RSA key and is signed using RSASSA-PSS, aligning with recommendations such as BSI TR-02102-2.
Using the new provider options `key-size`, `algorithm` and `curve` of the `jgroups-mtls` SPI, administrators can choose a different RSA key size or switch to ECDSA.
When the stored certificate no longer matches the configuration, a node regenerates it on startup.
See the upgrading guide and the caching guide for details.

= Themes

== Login and welcome UI upgraded to PatternFly 6
Expand Down
15 changes: 15 additions & 0 deletions docs/documentation/upgrading/topics/changes/changes-27_0_0.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,21 @@ If you use auto-link flows with a SAML or custom identity provider that does not
Notable changes may include internal behavior changes that prevent common misconfigurations, bugs that are fixed, or changes to simplify running {project_name}.
It also lists significant changes to internal APIs.

=== Cache transport certificate uses RSA 3072 bits

The automatically generated certificate that secures the communication between {project_name} nodes now uses a 3072-bit RSA key instead of a 2048-bit RSA key.
It is signed using RSASSA-PSS instead of RSASSA-PKCS1-v1_5.
This aligns with recommendations such as BSI TR-02102-2, which asks for RSA keys of at least 3000 bits.

When a node starts and the certificate stored in the database was generated with a different key, the node generates a new certificate and stores it.
Running nodes reload it when they reject the connection of the restarted node.
During a rolling upgrade, this can cause short-lived connection retries.

To keep the previous key size, set the SPI option `+spi-jgroups-mtls--default--key-size=2048+`.
To use an ECDSA key instead, set `+spi-jgroups-mtls--default--algorithm=ECDSA+`, and optionally `+spi-jgroups-mtls--default--curve+`.
Configure the same values on all nodes.
For more information, check the link:https://www.keycloak.org/server/caching#_securing_transport_stacks[Securing Transport Stacks] in the distributed caches guide.

=== Existing AES key sizes are recorded during migration

When upgrading, existing `aes-generated` key providers without an explicit `secretSize` are updated to record the size of their stored key, including databases already running 26.8.x.
Expand Down
8 changes: 7 additions & 1 deletion docs/guides/server/caching.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -281,11 +281,17 @@ The transport stack ensures that {project_name} nodes in a cluster communicate i
Communication between nodes is encrypted using TLS by default.
No additional CLI options or modifications of the cache XML are required.

With TLS enabled, {project_name} auto-generates a self-signed RSA 2048 bit certificate to secure the connection and uses TLS 1.3 to secure the communication.
With TLS enabled, {project_name} auto-generates a self-signed RSA 3072 bit certificate to secure the connection and uses TLS 1.3 to secure the communication.
The certificate is signed with RSASSA-PSS.
The keys and the certificate are stored in the database so they are available to all nodes.
By default, the certificate is valid for 60 days and is rotated at runtime every 30 days.
Use the option `cache-embedded-mtls-rotation-interval-days` to change this.

Use the `+spi-jgroups-mtls--default--...+` SPI options if there is a compliance need to change them, otherwise use the default settings. When a node starts and the stored certificate does not match the configured algorithm and key size or curve, the node generates a new certificate, stores it in the database and the other nodes in the cluster will reload it. Configure the same values on all nodes.
Otherwise, nodes with different values regenerate the certificate each time one of them starts.

These options only apply to the generated certificate and are ignored when you provide your own keystore.

=== Running inside a service mesh

Keep {project_name}'s transport encryption enabled when running inside a service mesh.
Expand Down
5 changes: 5 additions & 0 deletions model/infinispan/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,11 @@
<scope>provided</scope>
</dependency>

<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-crypto-default</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,20 @@ public class DatabaseJGroupsCertificateProvider implements JGroupsCertificatePro
private final Lock lock = new ReentrantLock();
// not final to be updated for testing
private volatile Duration rotationPeriod;
private final KeySpec keySpec;
private volatile JGroupsCertificate currentCertificate;

private DatabaseJGroupsCertificateProvider(KeycloakSessionFactory sessionFactory, Duration rotationPeriod) {
private DatabaseJGroupsCertificateProvider(KeycloakSessionFactory sessionFactory, Duration rotationPeriod, KeySpec keySpec) {
this.keySpec = Objects.requireNonNull(keySpec);
this.sessionFactory = Objects.requireNonNull(sessionFactory);
this.rotationPeriod = Objects.requireNonNull(rotationPeriod);
keyManager = new ReloadingX509ExtendedKeyManager();
trustManager = new ReloadingX509ExtendedTrustManager();
currentCertificate = new JGroupsCertificate();
}

public static DatabaseJGroupsCertificateProvider create(KeycloakSessionFactory factory, Duration rotationPeriod) {
var provider = new DatabaseJGroupsCertificateProvider(factory, rotationPeriod);
public static DatabaseJGroupsCertificateProvider create(KeycloakSessionFactory factory, Duration rotationPeriod, KeySpec keySpec) {
var provider = new DatabaseJGroupsCertificateProvider(factory, rotationPeriod, keySpec);
provider.init();
return provider;
}
Expand Down Expand Up @@ -180,6 +182,9 @@ private void useCertificate(JGroupsCertificate certificate) {
currentCertificate = certificate;
keyManager.reload(km);
trustManager.reload(tm);
var x509 = certificate.getCertificate();
logger.infof("JGroups mTLS certificate in use: key=%s, signature=%s, valid until %s, rotation every %s.",
keySpec.description(), x509.getSigAlgName(), x509.getNotAfter().toInstant(), rotationPeriod);
} catch (GeneralSecurityException | IOException e) {
throw new RuntimeException(e);
} finally {
Expand All @@ -189,10 +194,22 @@ private void useCertificate(JGroupsCertificate certificate) {

private JGroupsCertificate loadOrCreateCertificate(KeycloakSession session) {
var storage = session.getProvider(ServerConfigStorageProvider.class);
return fromJson(storage.loadOrCreate(CERTIFICATE_ID, this::generateSelfSignedCertificate));
var stored = fromJson(storage.loadOrCreate(CERTIFICATE_ID, this::generateSelfSignedCertificate));
if (matchesKeySpec(stored)) {
return stored;
}
// Replace only if still mismatching, so concurrently starting nodes with the same configuration regenerate it once.
// Running nodes reload the new certificate when the trust manager rejects the connection of this node.
logger.infof("Stored JGroups certificate does not match the configured key (%s). Regenerating it.", keySpec.description());
storage.replace(CERTIFICATE_ID, json -> !matchesKeySpec(fromJson(json)), this::generateSelfSignedCertificate);
return fromJson(storage.find(CERTIFICATE_ID).orElseThrow());
Comment thread
ahus1 marked this conversation as resolved.
Resolved
}

private boolean matchesKeySpec(JGroupsCertificate certificate) {
return keySpec.matches(certificate.getCertificate().getPublicKey());
}

private String generateSelfSignedCertificate() {
return toJson(Utils.generateSelfSignedCertificate(rotationPeriod.multipliedBy(2L)));
return toJson(Utils.generateSelfSignedCertificate(rotationPeriod.multipliedBy(2L), keySpec));
}
}
Loading
Loading
0