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
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<String> x5c,
String algorithm, String issuer) throws VerificationException {

String configValue = Optional.ofNullable(context.getClient())
.map(client -> client.getAttribute(OAUTH_CLIENT_ATTESTATION_CONFIG_TRUST_IDPS))
Expand All @@ -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);
}
Comment thread
adityaanikam marked this conversation as resolved.
Resolved
Comment thread
adityaanikam marked this conversation as resolved.
Resolved
Comment thread
adityaanikam marked this conversation as resolved.
Resolved

if (Strings.isEmpty(kid))
throw new IllegalArgumentException("Invalid attester kid: " + kid);
Comment thread
adityaanikam marked this conversation as resolved.
Resolved

JWK jwk = resolver.resolveKey(context.getSession(), configValue, request)
.orElseThrow(() -> new IllegalStateException("No matching key found for kid: " + kid));

return toPublicKeyWrapper(jwk);
Expand Down Expand Up @@ -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
//
Expand Down
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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;
Expand All @@ -40,6 +49,8 @@

public final class OID4VCProofTestUtils {

private static final SecureRandom SECURE_RANDOM = new SecureRandom();

private OID4VCProofTestUtils() {
}

Expand Down Expand Up @@ -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);
}
}
Comment thread
adityaanikam marked this conversation as resolved.
Resolved

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()));
Comment thread
adityaanikam marked this conversation as resolved.
Resolved
}

// 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<JWK> jwkList = Arrays.stream(keys)
.map(JWKSServerUtils::toJwk)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -61,6 +73,7 @@
public class OIDCAttestationBasedClientAuthenticationTest extends OID4VCIssuerTestBase {

private static OIDCClientAttester attester;
private static KeyWrapper attesterKeyWrapper;
private static String attesterJwks;

@TestSetup
Expand All @@ -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);
}

Expand Down Expand Up @@ -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(" ", "-"));
Comment thread
adityaanikam marked this conversation as resolved.
Resolved
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();
}
}
Loading