From b04d334be6aae228f8248def9586f675479ac213 Mon Sep 17 00:00:00 2001 From: adityaanikam Date: Thu, 17 Sep 2026 14:37:27 +0530 Subject: [PATCH] Resolve ABCA attester key from x5c JOSE header AttestationBasedClientAuthenticator.findAttesterKey required a kid and looked it up via JWKS, rejecting any Client Attestation JWT that carries its signing certificate chain in the x5c header instead, with "Invalid attester kid: null". x5c was never read. Prefer x5c when present: validate the chain against the X.509 trust anchors of the configured attester_trust_idps using TrustMaterialResolver.validateX509Chain, the mechanism #51042 added for key attestations, and use the leaf certificate's public key. Fall back to the existing kid/JWKS path when x5c is absent. Closes #52766 Signed-off-by: adityaanikam --- .../AttestationBasedClientAuthenticator.java | 26 +++- .../tests/oid4vc/OID4VCProofTestUtils.java | 57 +++++++++ ...estationBasedClientAuthenticationTest.java | 120 ++++++++++++++++++ 3 files changed, 197 insertions(+), 6 deletions(-) diff --git a/services/src/main/java/org/keycloak/authentication/authenticators/client/AttestationBasedClientAuthenticator.java b/services/src/main/java/org/keycloak/authentication/authenticators/client/AttestationBasedClientAuthenticator.java index c1ef7b3bb8c1..f856102c8c81 100644 --- a/services/src/main/java/org/keycloak/authentication/authenticators/client/AttestationBasedClientAuthenticator.java +++ b/services/src/main/java/org/keycloak/authentication/authenticators/client/AttestationBasedClientAuthenticator.java @@ -37,6 +37,7 @@ import org.keycloak.broker.provider.TrustMaterialRequest; import org.keycloak.broker.provider.TrustMaterialResolver; import org.keycloak.common.Profile; +import org.keycloak.common.VerificationException; import org.keycloak.common.util.Base64Url; import org.keycloak.crypto.KeyUse; import org.keycloak.crypto.KeyWrapper; @@ -312,10 +313,8 @@ public ClientAttestationPoPJwt issuedNowWithTTL(int ttl) { // Private --------------------------------------------------------------------------------------------------------- - private KeyWrapper findAttesterKey(ClientAuthenticationFlowContext context, String kid, String algorithm, String issuer) { - - if (Strings.isEmpty(kid)) - throw new IllegalArgumentException("Invalid attester kid: " + kid); + private KeyWrapper findAttesterKey(ClientAuthenticationFlowContext context, String kid, List x5c, + String algorithm, String issuer) throws VerificationException { String configValue = Optional.ofNullable(context.getClient()) .map(client -> client.getAttribute(OAUTH_CLIENT_ATTESTATION_CONFIG_TRUST_IDPS)) @@ -328,7 +327,22 @@ private KeyWrapper findAttesterKey(ClientAuthenticationFlowContext context, Stri .algorithm(algorithm) .issuer(issuer) .build(); - JWK jwk = new TrustMaterialResolver().resolveKey(context.getSession(), configValue, request) + TrustMaterialResolver resolver = new TrustMaterialResolver(); + + if (x5c != null && !x5c.isEmpty()) { + JWK jwk = resolver.validateX509Chain(context.getSession(), configValue, request, x5c, algorithm); + if (jwk != null) + return toPublicKeyWrapper(jwk); + // null means no X.509 trust anchors are configured (JWKS-only), while a configured chain that + // fails validation throws. Fall back to the kid lookup when there is a kid. + if (Strings.isEmpty(kid)) + throw new IllegalStateException("No X.509 trust anchors are configured to validate the x5c chain in: " + OAUTH_CLIENT_ATTESTATION_CONFIG_TRUST_IDPS); + } + + if (Strings.isEmpty(kid)) + throw new IllegalArgumentException("Invalid attester kid: " + kid); + + JWK jwk = resolver.resolveKey(context.getSession(), configValue, request) .orElseThrow(() -> new IllegalStateException("No matching key found for kid: " + kid)); return toPublicKeyWrapper(jwk); @@ -398,7 +412,7 @@ private void validateClientAttestationJwt(ClientAuthenticationFlowContext contex // The signature of the Client Attestation JWT verifies with the public key of a known and trusted Attester // - KeyWrapper attesterKey = findAttesterKey(context, jws.getHeader().getKeyId(), jws.getHeader().getRawAlgorithm(), attestationJwt.getIssuer()); + KeyWrapper attesterKey = findAttesterKey(context, jws.getHeader().getKeyId(), jws.getHeader().getX5c(), jws.getHeader().getRawAlgorithm(), attestationJwt.getIssuer()); // Client Attestation JWT verification without signature check // diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCProofTestUtils.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCProofTestUtils.java index cd47b7f17779..9c67f4f1f489 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCProofTestUtils.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/OID4VCProofTestUtils.java @@ -1,13 +1,17 @@ package org.keycloak.tests.oid4vc; import java.math.BigInteger; +import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; +import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPublicKey; +import java.time.Instant; +import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Date; import java.util.List; @@ -31,6 +35,11 @@ import org.keycloak.representations.AccessToken; import org.bouncycastle.asn1.x500.X500Name; +import org.bouncycastle.asn1.x509.BasicConstraints; +import org.bouncycastle.asn1.x509.Extension; +import org.bouncycastle.asn1.x509.KeyUsage; +import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo; +import org.bouncycastle.cert.CertIOException; import org.bouncycastle.cert.X509v3CertificateBuilder; import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter; import org.bouncycastle.cert.jcajce.JcaX509v3CertificateBuilder; @@ -40,6 +49,8 @@ public final class OID4VCProofTestUtils { + private static final SecureRandom SECURE_RANDOM = new SecureRandom(); + private OID4VCProofTestUtils() { } @@ -189,6 +200,52 @@ public static KeyWrapper createRsaKeyPair(String keyId) { } } + public static X509Certificate createCaCertificate(KeyPair caKeyPair, String commonName) { + X500Name caName = new X500Name("CN=" + commonName); + try { + X509v3CertificateBuilder builder = certificateBuilder(caName, caName, caKeyPair); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(true)); + builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.keyCertSign | KeyUsage.cRLSign)); + return signCertificate(builder, caKeyPair); + } catch (CertIOException | OperatorCreationException | CertificateException e) { + throw new RuntimeException(e); + } + } + + public static X509Certificate createEndEntityCertificate(KeyPair subjectKeyPair, KeyPair caKeyPair, + X509Certificate caCertificate, String commonName) { + X500Name issuer = new X500Name(caCertificate.getSubjectX500Principal().getName()); + X500Name subject = new X500Name("CN=" + commonName); + try { + X509v3CertificateBuilder builder = certificateBuilder(issuer, subject, subjectKeyPair); + builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); + builder.addExtension(Extension.keyUsage, true, new KeyUsage(KeyUsage.digitalSignature)); + return signCertificate(builder, caKeyPair); + } catch (CertIOException | OperatorCreationException | CertificateException e) { + throw new RuntimeException(e); + } + } + + private static X509v3CertificateBuilder certificateBuilder(X500Name issuer, X500Name subject, + KeyPair subjectKeyPair) { + Instant now = Instant.now(); + return new X509v3CertificateBuilder( + issuer, + new BigInteger(160, SECURE_RANDOM), + Date.from(now.minus(1, ChronoUnit.DAYS)), + Date.from(now.plus(365, ChronoUnit.DAYS)), + subject, + SubjectPublicKeyInfo.getInstance(subjectKeyPair.getPublic().getEncoded())); + } + + // RSA-only: the signing key pair here always comes from an RSA test key generator in this + // class, so the algorithm is fixed rather than derived from the key type. + private static X509Certificate signCertificate(X509v3CertificateBuilder builder, KeyPair signingKeyPair) + throws OperatorCreationException, CertificateException { + ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").build(signingKeyPair.getPrivate()); + return new JcaX509CertificateConverter().getCertificate(builder.build(signer)); + } + public static JSONWebKeySet toJwks(KeyWrapper... keys) { List jwkList = Arrays.stream(keys) .map(JWKSServerUtils::toJwk) diff --git a/tests/base/src/test/java/org/keycloak/tests/oid4vc/abca/OIDCAttestationBasedClientAuthenticationTest.java b/tests/base/src/test/java/org/keycloak/tests/oid4vc/abca/OIDCAttestationBasedClientAuthenticationTest.java index 552a86e5dade..9bdf16c58527 100644 --- a/tests/base/src/test/java/org/keycloak/tests/oid4vc/abca/OIDCAttestationBasedClientAuthenticationTest.java +++ b/tests/base/src/test/java/org/keycloak/tests/oid4vc/abca/OIDCAttestationBasedClientAuthenticationTest.java @@ -16,20 +16,28 @@ */ package org.keycloak.tests.oid4vc.abca; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.PrivateKey; import java.security.PublicKey; +import java.security.cert.X509Certificate; import java.util.List; import java.util.Map; +import org.keycloak.OAuthErrorException; import org.keycloak.TokenVerifier; import org.keycloak.authentication.authenticators.client.AttestationBasedClientAuthenticator.ClientAttestationJwt; import org.keycloak.authentication.authenticators.client.AttestationBasedClientAuthenticator.ClientAttestationPoPJwt; import org.keycloak.broker.trust.DefaultTrustIdentityProviderConfig; import org.keycloak.broker.trust.DefaultTrustIdentityProviderFactory; import org.keycloak.common.VerificationException; +import org.keycloak.common.util.PemUtils; +import org.keycloak.crypto.AsymmetricSignatureSignerContext; import org.keycloak.crypto.KeyWrapper; import org.keycloak.jose.jwk.JSONWebKeySet; import org.keycloak.jose.jwk.JWK; import org.keycloak.jose.jwk.JWKBuilder; +import org.keycloak.jose.jws.JWSBuilder; import org.keycloak.models.RealmModel; import org.keycloak.protocol.oid4vc.model.CredentialResponse; import org.keycloak.protocol.oid4vc.model.Proofs; @@ -46,11 +54,15 @@ import org.junit.jupiter.api.Test; import static org.keycloak.authentication.authenticators.client.AttestationBasedClientAuthenticator.OAUTH_CLIENT_ATTESTATION_HEADER; +import static org.keycloak.authentication.authenticators.client.AttestationBasedClientAuthenticator.OAUTH_CLIENT_ATTESTATION_JWT_TYPE; import static org.keycloak.authentication.authenticators.client.AttestationBasedClientAuthenticator.OAUTH_CLIENT_ATTESTATION_POP_HEADER; import static org.keycloak.protocol.oidc.OIDCLoginProtocol.ATTEST_JWT_CLIENT_AUTH; +import static org.keycloak.tests.oid4vc.OID4VCProofTestUtils.createCaCertificate; +import static org.keycloak.tests.oid4vc.OID4VCProofTestUtils.createEndEntityCertificate; import static org.keycloak.tests.oid4vc.OID4VCProofTestUtils.createRsaKeyPair; import static org.keycloak.tests.oid4vc.OID4VCTestContext.CLIENT_ATTESTER_ATTACHMENT_KEY; +import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; @@ -61,6 +73,7 @@ public class OIDCAttestationBasedClientAuthenticationTest extends OID4VCIssuerTestBase { private static OIDCClientAttester attester; + private static KeyWrapper attesterKeyWrapper; private static String attesterJwks; @TestSetup @@ -73,6 +86,7 @@ public void configure() throws Exception { JSONWebKeySet jwks = new JSONWebKeySet(); jwks.setKeys(new JWK[] { jwk }); attesterJwks = JsonSerialization.writeValueAsString(jwks); + attesterKeyWrapper = kw; attester = new OIDCMockClientAttester(kw); } @@ -194,4 +208,110 @@ public void testClientAttestationHappyFlow() { assertFalse(credResponse.getCredentials().isEmpty(), "No credential"); } + + @Test + public void testClientAttestationHappyFlowWithX5c() throws Exception { + runX5cAttestationTest("Test CA", "Test CA", true); + } + + @Test + public void testClientAttestationX5cUntrustedChainIsRejected() throws Exception { + runX5cAttestationTest("Trusted CA", "Untrusted CA", false); + } + + @Test + public void testClientAttestationWithKidAndX5cFallsBackToKidWithoutX509TrustAnchors() throws Exception { + // The default trust IdP only has the attester JWKS, so there are no X.509 trust anchors and + // validateX509Chain returns null. The kid must still be used, as it was before x5c support. + KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); + kpg.initialize(2048); + + KeyPair caKeyPair = kpg.generateKeyPair(); + X509Certificate caCert = createCaCertificate(caKeyPair, "Unused CA"); + KeyPair leafKeyPair = kpg.generateKeyPair(); + X509Certificate leafCert = createEndEntityCertificate(leafKeyPair, caKeyPair, caCert, "ABCA Test Attester"); + + AccessTokenResponse tokenResponse = requestTokenWithX5cAttestation(leafCert, attesterKeyWrapper); + + assertNull(tokenResponse.getErrorDescription(), "Token request error: " + tokenResponse.getErrorDescription()); + assertNotNull(tokenResponse.getAccessToken(), "No access token"); + } + + private void runX5cAttestationTest(String trustedCaName, String signingCaName, boolean expectSuccess) throws Exception { + KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); + kpg.initialize(2048); + + KeyPair trustedCaKeyPair = kpg.generateKeyPair(); + X509Certificate trustedCaCert = createCaCertificate(trustedCaKeyPair, trustedCaName); + + KeyPair signingCaKeyPair = trustedCaName.equals(signingCaName) + ? trustedCaKeyPair + : kpg.generateKeyPair(); + X509Certificate signingCaCert = trustedCaName.equals(signingCaName) + ? trustedCaCert + : createCaCertificate(signingCaKeyPair, signingCaName); + + // The attester key has no kid, so this covers the x5c-only case from #52766. + var attesterKw = createRsaKeyPair("openid-abca-attester-x5c-" + signingCaName.replace(" ", "-")); + attesterKw.setKid(null); + KeyPair attesterKeyPair = new KeyPair((PublicKey) attesterKw.getPublicKey(), (PrivateKey) attesterKw.getPrivateKey()); + X509Certificate attesterCert = createEndEntityCertificate(attesterKeyPair, signingCaKeyPair, signingCaCert, "ABCA Test Attester"); + attesterKw.setCertificate(attesterCert); + + runOnServer.run(session -> { + RealmModel realm = session.getContext().getRealm(); + configureTrustIdentityProvider(realm, OAUTH_CLIENT_ATTESTATION_DEFAULT_TRUST_IDP_ALIAS, + DefaultTrustIdentityProviderFactory.PROVIDER_ID, + Map.of(DefaultTrustIdentityProviderConfig.USE_X509, "true", + DefaultTrustIdentityProviderConfig.TRUSTED_CERTIFICATES, + PemUtils.encodeCertificate(trustedCaCert))); + }); + + AccessTokenResponse tokenResponse = requestTokenWithX5cAttestation(attesterCert, attesterKw); + + if (expectSuccess) { + assertNull(tokenResponse.getErrorDescription(), "Token request error: " + tokenResponse.getErrorDescription()); + assertNotNull(tokenResponse.getAccessToken(), "No access token"); + } else { + assertEquals(OAuthErrorException.INVALID_CLIENT_ATTESTATION, tokenResponse.getError(), + "Expected the untrusted x5c chain to be rejected with invalid_client_attestation"); + assertNull(tokenResponse.getAccessToken(), "Untrusted x5c chain must not yield an access token"); + } + } + + private AccessTokenResponse requestTokenWithX5cAttestation(X509Certificate x5cCert, KeyWrapper attesterSigningKey) throws Exception { + var ctx = new OID4VCTestContext(abcaClient, sdJwtTypeCredentialScope); + var walletKey = wallet.getRSAKeyPair(ctx); + JWK walletJwk = JWKBuilder.create() + .kid(walletKey.getKid()) + .algorithm(walletKey.getAlgorithm()) + .rsa(walletKey.getPublicKey()); + ClientAttestationJwt body = new ClientAttestationJwt() + .issuer("https://example.com/mock-attester") + .subject(abcaClient.getClientId()) + .confirmation(walletJwk) + .issuedNowWithTTL(300); + + String attestationJwt = new JWSBuilder() + .type(OAUTH_CLIENT_ATTESTATION_JWT_TYPE) + .x5c(List.of(x5cCert)) + .jsonContent(body) + .sign(new AsymmetricSignatureSignerContext(attesterSigningKey)); + + String attestationPoPJwt = wallet.buildClientAttestationPoPJWT(ctx, walletKey); + KeyWrapper ecKey = wallet.getECKeyPair(ctx); + + AuthorizationEndpointResponse authResponse = wallet.authorizationRequest() + .scope(ctx.getScope()) + .send(ctx.getHolder(), TEST_PASSWORD); + String authCode = authResponse.getCode(); + assertNotNull(authCode, "No auth code"); + + String tokenEndpoint = oauth.getEndpoints().getToken(); + return wallet.accessTokenRequest(ctx, authCode) + .header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt) + .header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, attestationPoPJwt) + .dpopProof(wallet.generateSignedDPoPProof(tokenEndpoint, ecKey, null)) + .send(); + } }