FFFF Reject reused and stale ABCA Client Attestation PoP JWTs by edewit · Pull Request #54367 · keycloak/keycloak · GitHub
[go: up one dir, main page]

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 @@ -39,6 +39,7 @@
import org.keycloak.common.Profile;
import org.keycloak.common.VerificationException;
import org.keycloak.common.util.Base64Url;
import org.keycloak.common.util.Time;
import org.keycloak.crypto.KeyUse;
import org.keycloak.crypto.KeyWrapper;
import org.keycloak.crypto.SignatureProvider;
Expand All @@ -48,10 +49,12 @@
import org.keycloak.jose.jwk.JWKParser;
import org.keycloak.jose.jws.Algorithm;
import org.keycloak.jose.jws.JWSInput;
import org.keycloak.jose.jws.crypto.HashUtils;
import org.keycloak.models.AuthenticationExecutionModel;
import org.keycloak.models.ClientModel;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.models.SingleUseObjectProvider;
import org.keycloak.protocol.oidc.OIDCLoginProtocol;
import org.keycloak.protocol.oidc.OIDCWellKnownProviderFactory;
import org.keycloak.protocol.oidc.representations.OIDCConfigurationRepresentation;
Expand All @@ -67,6 +70,7 @@
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.apache.commons.codec.binary.Hex;

import static jakarta.ws.rs.core.Response.Status.BAD_REQUEST;

Expand Down Expand Up @@ -100,6 +104,18 @@ public class AttestationBasedClientAuthenticator extends AbstractClientAuthentic
/** The token confirmation type */
public static final String ABCA_JKT_TYPE = "Client-Attestation";

/**
* Maximum acceptable age of a Client Attestation PoP JWT based on its {@code iat} claim,
* aligned with {@link org.keycloak.services.util.DPoPUtil#DEFAULT_PROOF_LIFETIME}.
*/
public static final int DEFAULT_POP_LIFETIME_SECONDS = 10;

/**
* Allowed clock skew when validating PoP {@code iat},
* aligned with {@link org.keycloak.services.util.DPoPUtil#DEFAULT_ALLOWED_CLOCK_SKEW}.
*/
public static final int DEFAULT_POP_CLOCK_SKEW_SECONDS = 15;
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.

It's not really a default because it cant currently be changed. From my experience, there are a lot of devices with messed up time settings out there. Especially mobile phones managed by corporations (and ABCA will be primarily used by Wallets on mobile phones initially).

Could this be made configurable? Or at least provide some way to override the default via parameters/config?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Do you have concrete ABCA case where 15s isn’t enough? These values intentionally match DPoPUtil.DEFAULT_PROOF_LIFETIME / DEFAULT_ALLOWED_CLOCK_SKEW, which also aren’t admin-configurable.


@Override
public String getId() {
return PROVIDER_ID;
Expand Down Expand Up @@ -468,6 +484,17 @@ private void validateClientAttestationPoPJwt(ClientAuthenticationFlowContext con
return true;
};

TokenVerifier.Predicate<JsonWebToken> iatFreshnessCheck = (t) -> {
long now = Time.currentTime();
long iat = t.getIat();
// Same window semantics as DPoP: iat - skew <= now <= iat + lifetime + skew
if (!(iat <= now + DEFAULT_POP_CLOCK_SKEW_SECONDS
&& iat >= now - DEFAULT_POP_LIFETIME_SECONDS - DEFAULT_POP_CLOCK_SKEW_SECONDS)) {
throw new TokenVerificationException(t, "Client Attestation PoP is not fresh enough");
}
return true;
};

TokenVerifier.Predicate<JsonWebToken> issCheck = (t) -> {
if (Strings.isEmpty(t.getIssuer()) || !t.getIssuer().equals(attestationJwt.getSubject()))
throw new TokenVerificationException(t, "The value of the iss (issuer) claim, representing the client_id MUST match the value of the sub (subject) claim in the Client Attestation");
Expand All @@ -491,7 +518,7 @@ private void validateClientAttestationPoPJwt(ClientAuthenticationFlowContext con
// Client Attestation PoP JWT verification without signature check
//
TokenVerifier.createWithoutSignature(attestationPoPJwt)
.withChecks(jtiCheck, iatCheck, issCheck, audCheck)
.withChecks(jtiCheck, iatCheck, iatFreshnessCheck, issCheck, audCheck)
.verify();

// Client Attestation PoP JWT signature check
Expand All @@ -506,13 +533,25 @@ private void validateClientAttestationPoPJwt(ClientAuthenticationFlowContext con
throw new TokenSignatureInvalidException(attestationPoPJwt, "Invalid token signature");
}

abcaResult.setAttestationPoPJwt(attestationPoPJwt);
rejectReplay(session, attestationPoPJwt);

// [TODO] The authorization server can utilize the jti value for replay attack detection
// [TODO] The authorization server may reject JWTs with an "iat" claim value that is unreasonably far in the past
abcaResult.setAttestationPoPJwt(attestationPoPJwt);

// [TODO] If the server provided a challenge value to the client, the challenge claim is present in the Client Attestation PoP JWT and matches the server-provided challenge value.
// [TODO] Additional checks to guarantee replay protection for the Client Attestation PoP JWT might need to be applied
}

private void rejectReplay(KeycloakSession session, ClientAttestationPoPJwt attestationPoPJwt) throws TokenVerificationException {
SingleUseObjectProvider singleUseCache = session.singleUseObjects();
// Namespace + realm isolate ABCA PoP jtis from other single-use entries and other realms
String realmId = session.getContext().getRealm().getId();
String hashKey = "abca-pop\n" + realmId + "\n" + attestationPoPJwt.getId() + "\n" + attestationPoPJwt.getIssuer();
String hashString = Hex.encodeHexString(HashUtils.hash("SHA1", hashKey.getBytes(StandardCharsets.UTF_8)));
// +1 covers the inclusive freshness boundary where JPA treats expire <= now as expired
int lifespan = Math.max(1, (int) (attestationPoPJwt.getIat() + DEFAULT_POP_LIFETIME_SECONDS
+ DEFAULT_POP_CLOCK_SKEW_SECONDS - Time.currentTime()) + 1);
Comment on lines +550 to +551
if (!singleUseCache.putIfAbsent(hashString, lifespan)) {
throw new TokenVerificationException(attestationPoPJwt, "Client Attestation PoP has already been used");
}
}

public static class ABCAResult {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ public String buildClientAttestationJWT(OID4VCTestContext ctx, KeyWrapper wallet
}

public String buildClientAttestationPoPJWT(OID4VCTestContext ctx, KeyWrapper walletKey) {
return buildClientAttestationPoPJWT(ctx, walletKey, Time.currentTime());
}

public String buildClientAttestationPoPJWT(OID4VCTestContext ctx, KeyWrapper walletKey, long iat) {
var issuer = getIssuerMetadata(ctx).getCredentialIssuer();

// Build Client Attestation PoP JWT
Expand All @@ -235,15 +239,16 @@ public String buildClientAttestationPoPJWT(OID4VCTestContext ctx, KeyWrapper wal
ClientAttestationPoPJwt body = new ClientAttestationPoPJwt()
.audience(issuer)
.issuer(clientId)
.issuedNowWithTTL(300) // 5min
.randomId();
body.iat(iat);
body.nbf(iat);
body.exp(iat + 300);

String attestationPoPJwt = new JWSBuilder()
return new JWSBuilder()
.type(OAUTH_CLIENT_ATTESTATION_POP_JWT_TYPE)
.kid(walletKey.getKid())
.jsonContent(body)
.sign(new AsymmetricSignatureSignerContext(walletKey));
return attestationPoPJwt;
}

public Proofs generateAttestationProof(OID4VCTestContext ctx, KeyWrapper attestationKey) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public void testIssuerHappyFlow() throws Exception {

AccessTokenResponse tokenResponse = wallet.accessTokenRequest(ctx, authCode)
.header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, attestationPoPJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, wallet.buildClientAttestationPoPJWT(ctx, rsaKey))
.codeVerifier(pkce)
.dpopProof(dpopProof)
.send();
Expand Down Expand Up @@ -245,7 +245,7 @@ public void testBatchIssuanceHappyFlow() throws Exception {

AccessTokenResponse tokenResponse = wallet.accessTokenRequest(ctx, authCode)
.header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, attestationPoPJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, wallet.buildClientAttestationPoPJWT(ctx, rsaKey))
.codeVerifier(pkce)
.dpopProof(dpopProof)
.send();
Expand Down Expand Up @@ -523,7 +523,7 @@ public void testRefreshTokenHappyFlow() throws Exception {

AccessTokenResponse tokenResponse = wallet.accessTokenRequest(ctx, authCode)
.header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, attestationPoPJwt)
BD0 .header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, wallet.buildClientAttestationPoPJWT(ctx, abcaKey))
.codeVerifier(pkce)
.dpopProof(dpopProof)
.send();
Expand Down Expand Up @@ -582,7 +582,7 @@ public void testRefreshTokenHappyFlow() throws Exception {
dpopProof = wallet.generateSignedDPoPProof(tokenEndpoint, ecKey, encodedRefreshToken);
tokenResponse = oauth.refreshRequest(encodedRefreshToken)
.header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, attestationPoPJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, wallet.buildClientAttestationPoPJWT(ctx, abcaKey))
.dpopProof(dpopProof)
.send();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,14 @@

import org.keycloak.OAuthErrorException;
import org.keycloak.TokenVerifier;
import org.keycloak.authentication.authenticators.client.AttestationBasedClientAuthenticator;
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.common.util.Time;
import org.keycloak.crypto.AsymmetricSignatureSignerContext;
import org.keycloak.crypto.KeyWrapper;
import org.keycloak.jose.jwk.JSONWebKeySet;
Expand Down Expand Up @@ -314,4 +316,98 @@ private AccessTokenResponse requestTokenWithX5cAttestation(X509Certificate x5cCe
.dpopProof(wallet.generateSignedDPoPProof(tokenEndpoint, ecKey, null))
.send();
}

@Test
public void testClientAttestationPoPReplayRejected() {
var ctx = new OID4VCTestContext(abcaClient, sdJwtTypeCredentialScope);
ctx.putAttachment(CLIENT_ATTESTER_ATTACHMENT_KEY, attester);

var kw = wallet.getRSAKeyPair(ctx);
String attestationJwt = wallet.buildClientAttestationJWT(ctx, kw);
String attestationPoPJwt = wallet.buildClientAttestationPoPJWT(ctx, kw);
KeyWrapper ecKey = wallet.getECKeyPair(ctx);
String tokenEndpoint = oauth.getEndpoints().getToken();

String authCode1 = authorize(ctx);
AccessTokenResponse first = wallet.accessTokenRequest(ctx, authCode1)
.header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, attestationPoPJwt)
.dpopProof(wallet.generateSignedDPoPProof(tokenEndpoint, ecKey, null))
.send();
assertNull(first.getErrorDescription(), "First token request should succeed: " + first.getErrorDescription());
assertNotNull(first.getAccessToken());

String authCode2 = authorize(ctx);
AccessTokenResponse replay = wallet.accessTokenRequest(ctx, authCode2)
.header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, attestationPoPJwt)
.dpopProof(wallet.generateSignedDPoPProof(tokenEndpoint, ecKey, null))
.send();
assertEquals(OAuthErrorException.INVALID_CLIENT_ATTESTATION, replay.getError());
assertTrue(replay.getErrorDescription().contains("already been used"),
"Expected PoP replay rejection, was: " + replay.getErrorDescription());
}

@Test
public void testClientAttestationPoPFreshJtiAccepted() {
var ctx = new OID4VCTestContext(abcaClient, sdJwtTypeCredentialScope);
ctx.putAttachment(CLIENT_ATTESTER_ATTACHMENT_KEY, attester);

var kw = wallet.getRSAKeyPair(ctx);
String attestationJwt = wallet.buildClientAttestationJWT(ctx, kw);
KeyWrapper ecKey = wallet.getECKeyPair(ctx);
String tokenEndpoint = oauth.getEndpoints().getToken();

String authCode1 = authorize(ctx);
AccessTokenResponse first = wallet.accessTokenRequest(ctx, authCode1)
.header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, wallet.buildClientAttestationPoPJWT(ctx, kw))
.dpopProof(wallet.generateSignedDPoPProof(tokenEndpoint, ecKey, null))
.send();
assertNull(first.getErrorDescription(), "First token request should succeed: " + first.getErrorDescription());

String authCode2 = authorize(ctx);
AccessTokenResponse second = wallet.accessTokenRequest(ctx, authCode2)
.header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, wallet.buildClientAttestationPoPJWT(ctx, kw))
.dpopProof(wallet.generateSignedDPoPProof(tokenEndpoint, ecKey, null))
.send();
assertNull(second.getErrorDescription(), "Token request with a fresh PoP jti should succeed: " + second.getErrorDescription());
assertNotNull(second.getAccessToken());
}

@Test
public void testClientAttestationPoPStaleIatRejected() {
var ctx = new OID4VCTestContext(abcaClient, sdJwtTypeCredentialScope);
ctx.putAttachment(CLIENT_ATTESTER_ATTACHMENT_KEY, attester);

var kw = wallet.getRSAKeyPair(ctx);
String attestationJwt = wallet.buildClientAttestationJWT(ctx, kw);
long staleIat = Time.currentTime() - AttestationBasedClientAuthenticator.DEFAULT_POP_LIFETIME_SECONDS
- AttestationBasedClientAuthenticator.DEFAULT_POP_CLOCK_SKEW_SECONDS - 30L;
String stalePoP = wallet.buildClientAttestationPoPJWT(ctx, kw, staleIat);
KeyWrapper ecKey = wallet.getECKeyPair(ctx);
String tokenEndpoint = oauth.getEndpoints().getToken();

String authCode = authorize(ctx);
AccessTokenResponse response = wallet.accessTokenRequest(ctx, authCode)
.header(OAUTH_CLIENT_ATTESTATION_HEADER, attestationJwt)
.header(OAUTH_CLIENT_ATTESTATION_POP_HEADER, stalePoP)
.dpopProof(wallet.generateSignedDPoPProof(tokenEndpoint, ecKey, null))
.send();
assertEquals(OAuthErrorException.INVALID_CLIENT_ATTESTATION, response.getError());
assertTrue(response.getErrorDescription().contains("not fresh enough"),
"Expected stale PoP rejection, was: " + response.getErrorDescription());
}

private String authorize(OID4VCTestContext ctx) {
// Ensure a fresh login form; an existing SSO session would skip the username field.
wallet.logout(ctx.getHolder());
AuthorizationEndpointResponse authResponse = wallet.authorizationRequest()
.scope(ctx.getScope())
.send(ctx.getHolder(), TEST_PASSWORD);
assertNull(authResponse.getErrorDescription(), "Authorization error: " + authResponse.getErrorDescription());
assertNotNull(authResponse.getCode(), "No auth code");
return authResponse.getCode();
}
}
Loading
0