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
Original file line number Diff line number Diff line change
Expand Up @@ -222,15 +222,15 @@ Do not use a generated realm key to sign SD-JWT VCs. A generated key either has
Elliptic Curve cryptography with the P-256 curve and `ES256` algorithm is recommended for OpenID4VC. To configure a suitable signing key:

. Obtain a P-256 private key and a corresponding leaf certificate issued by a certificate authority. Include intermediate certificates when applicable. The example how to create valid ES256 key is in the https://github.com/keycloak/keycloak-playground/blob/main/fapi-playground/keystores/oid4vci-ssl-test/README-generate-keystore.md[Keycloak playground repository] (this is just for the development purposes and not officially supported).
. Store the private key and its certificate chain in a supported Java keystore. The private-key entry must contain the leaf certificate first, followed by any intermediate certificates. You may append a self-signed root certificate, but you must not append a non-self-signed certificate that is intended to be the trust anchor.
. Store the private key and its certificate chain in a supported Java keystore. The private-key entry must contain the leaf certificate first, followed by any intermediate certificates. You may then append a self-signed root certificate, but you must not append a non-self-signed certificate that is intended to be the trust anchor.
. In the Admin Console, go to *Realm Settings* > *Keys* > *Providers*.
. Add a *java-keystore* provider and configure the keystore path, type, passwords, and key alias.
. Set *Algorithm* to `ES256` and *Key use* to `sig`.
. Make the provider active and assign it sufficient priority to become the active `ES256` realm key. Alternatively, explicitly select this key as the *Signing Key ID* when configuring the credential client scope.

[NOTE]
====
The keystore may contain a self-signed root certificate so that {project_name} can load and validate the complete chain. {project_name} removes a trailing self-signed root certificate from the SD-JWT VC and signed issuer metadata `x5c` headers. It does not remove a non-self-signed trust anchor, which must therefore be omitted from the configured chain.
{project_name} can load a keystore whose chain does not end in a self-signed certificate, such as a lone leaf certificate. For both the SD-JWT VC and the signed issuer metadata `x5c` headers, {project_name} only removes trailing self-signed certificates, as they are treated as trust anchors. A non-self-signed trust anchor must therefore be omitted from the configured chain.

For details about the keystore location and provider fields, see <<realm_keys,Configuring realm keys>>.
====
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,16 +172,25 @@ private static void validateCertificateChain(List<X509Certificate> certificates)
return;
}

Set<TrustAnchor> anchors = new HashSet<>();
// The topmost certificate is the trust anchor; it must itself be valid (e.g. not expired).
X509Certificate top = certificates.get(certificates.size() - 1);
top.checkValidity();

// consider the last certificate in the chain as the most trusted cert
anchors.add(new TrustAnchor(certificates.get(certificates.size() - 1), null));
// A single certificate is not a chain; there is nothing further to validate.
if (certificates.size() == 1) {
return;
}

Set<TrustAnchor> anchors = new HashSet<>();
anchors.add(new TrustAnchor(top, null));

PKIXParameters params = new PKIXParameters(anchors);

params.setRevocationEnabled(false);

CertPath certPath = CertificateFactory.getInstance("X.509").generateCertPath(certificates);
// Validate the path from the leaf up to (but excluding) the trust anchor.
List<X509Certificate> path = certificates.subList(0, certificates.size() - 1);
CertPath certPath = CertificateFactory.getInstance("X.509").generateCertPath(path);
CertPathValidator validator = CertPathValidator.getInstance(CertPathValidator.getDefaultType());

validator.validate(certPath, params);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -341,10 +341,14 @@ private JsonWebToken createMetadataJwt(CredentialIssuer metadata, RealmModel rea
return jwt;
}

private void addCertificateHeaders(JWSBuilder jwsBuilder, KeyWrapper keyWrapper, RealmModel realm) {
protected void addCertificateHeaders(JWSBuilder jwsBuilder, KeyWrapper keyWrapper, RealmModel realm) {
if (keyWrapper.getCertificateChain() != null && !keyWrapper.getCertificateChain().isEmpty()) {
List<X509Certificate> certificateChain = new ArrayList<>(keyWrapper.getCertificateChain());
try {
// Exclude trailing self-signed certificates, which are trust anchors and must not be included in the
// x5c chain. See also [AS-AP-10-056](https://eudi.dev/3.0.0/annexes/annex-2/annex-2.03-high-level-requirements-by-category/#3-attestation-pid-providers).
// A non-self-signed trust anchor cannot be told apart from an issuing CA that wallets need to build
// the certificate path, so it must be left out of the configured chain instead.
Comment thread
IngridPuppet marked this conversation as resolved.
Resolved
while (certificateChain.size() > 1
&& CertificateUtils.isSelfSigned(certificateChain.get(certificateChain.size() - 1))) {
certificateChain.remove(certificateChain.size() - 1);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,17 +72,21 @@ public KeystoreInfo generateKeystore(File folder, KeystoreUtil.KeystoreFormat ke

public KeystoreInfo generateKeystore(File folder, KeystoreUtil.KeystoreFormat keystoreType,
String subject, String keystorePassword, String keyPassword, PrivateKey privKey, Certificate certificate) throws Exception {
return generateKeystore(folder, keystoreType, subject, keystorePassword, keyPassword, privKey, new Certificate[] { certificate });
}

public KeystoreInfo generateKeystore(File folder, KeystoreUtil.KeystoreFormat keystoreType,
String alias, String keystorePassword, String keyPassword, PrivateKey privKey, Certificate[] chain) throws Exception {
KeyStore keyStore = CryptoIntegration.getProvider().getKeyStore(keystoreType);
keyStore.load(null, null);
Certificate[] chain = {certificate};
keyStore.setKeyEntry(subject, privKey, keyPassword.trim().toCharArray(), chain);
keyStore.setKeyEntry(alias, privKey, keyPassword.trim().toCharArray(), chain);

File file = saveKeystore(folder, keystoreType, keyStore, keystorePassword);

CertificateRepresentation certRep = new CertificateRepresentation();
certRep.setPrivateKey(PemUtils.encodeKey(privKey));
certRep.setPublicKey(PemUtils.encodeKey(certificate.getPublicKey()));
certRep.setCertificate(PemUtils.encodeCertificate(certificate));
certRep.setPublicKey(PemUtils.encodeKey(chain[0].getPublicKey()));
certRep.setCertificate(PemUtils.encodeCertificate(chain[0]));
return new KeystoreInfo(certRep, file);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,28 @@ public void invalidKeystoreExpiredCertificate() throws Exception {
assertError(response, "Certificate error on server.");
}

@Test
public void createKeystoreWithSingleNonSelfSignedCertificate() throws Exception {
// A keystore whose only certificate is not self-signed (e.g. a leaf issued by an omitted CA) must be importable.
generateNonSelfSignedCertificateStore(cryptoHelper.keystore().getPreferredKeystoreType());
ComponentRepresentation rep = createRep("valid", System.currentTimeMillis(), keyAlgorithm);

Response response = realm.admin().components().add(rep);
String id = ApiUtil.getCreatedId(response);
realm.cleanup().add(r -> r.components().component(id).remove());
}

@Test
public void createKeystoreWithLeafAndNonSelfSignedTrustAnchor() throws Exception {
// A keystore holding a leaf and a non-self-signed trust anchor (two certificates) must be importable.
generateLeafWithNonSelfSignedTrustAnchorStore(cryptoHelper.keystore().getPreferredKeystoreType());
ComponentRepresentation rep = createRep("valid", System.currentTimeMillis(), keyAlgorithm);

Response response = realm.admin().components().add(rep);
String id = ApiUtil.getCreatedId(response);
realm.cleanup().add(r -> r.components().component(id).remove());
}

@Test
public void testExpiredCertificateInOneHour() throws Exception {
this.keyAlgorithm = Algorithm.RS256;
Expand Down Expand Up @@ -462,6 +484,30 @@ private void generateRSAExpiredInOneHourCertificateStore(KeystoreUtil.KeystoreFo
this.generatedKeystore = cryptoHelper.keystore().generateKeystore(folder, keystoreType, "keyalias", "password", "password", keyPair.getPrivate(), cert);
}

private void generateNonSelfSignedCertificateStore(KeystoreUtil.KeystoreFormat keystoreType) throws Exception {
// A leaf certificate issued by a CA that is deliberately not part of the keystore, so the only certificate in
// the store is not self-signed.
KeyPair caKeyPair = org.keycloak.common.util.KeyUtils.generateRsaKeyPair(2048);
X509Certificate caCert = CertificateUtils.generateV1SelfSignedCertificate(caKeyPair, "test-ca");
KeyPair leafKeyPair = org.keycloak.common.util.KeyUtils.generateRsaKeyPair(2048);
X509Certificate leafCert = CertificateUtils.generateV3Certificate(leafKeyPair, caKeyPair.getPrivate(), caCert, "test-leaf");
this.generatedKeystore = cryptoHelper.keystore().generateKeystore(folder, keystoreType, "keyalias", "password", "password",
leafKeyPair.getPrivate(), leafCert);
}

private void generateLeafWithNonSelfSignedTrustAnchorStore(KeystoreUtil.KeystoreFormat keystoreType) throws Exception {
// A keystore holding a leaf and a non-self-signed trust anchor (two certificates). The trust anchor is issued
// by an external root that is deliberately not part of the keystore, so it is not self-signed.
KeyPair rootKeyPair = org.keycloak.common.util.KeyUtils.generateRsaKeyPair(2048);
X509Certificate rootCert = CertificateUtils.generateV1SelfSignedCertificate(rootKeyPair, "test-external-root");
KeyPair anchorKeyPair = org.keycloak.common.util.KeyUtils.generateRsaKeyPair(2048);
X509Certificate anchorCert = CertificateUtils.generateV3Certificate(anchorKeyPair, rootKeyPair.getPrivate(), rootCert, "test-anchor");
KeyPair leafKeyPair = org.keycloak.common.util.KeyUtils.generateRsaKeyPair(2048);
X509Certificate leafCert = CertificateUtils.generateV3Certificate(leafKeyPair, anchorKeyPair.getPrivate(), anchorCert, "test-leaf");
this.generatedKeystore = cryptoHelper.keystore().generateKeystore(folder, keystoreType, "keyalias", "password", "password",
leafKeyPair.getPrivate(), new Certificate[] { leafCert, anchorCert });
}

private String getKeyKID(String providerId) {
KeysMetadataRepresentation metadata = realm.admin().keys().getKeyMetadata();
KeyMetadataRepresentation key = metadata.getKeys().stream().filter(k -> k.getProviderId().equals(providerId)).findFirst().orElse(null);
Expand Down
Loading
Loading