8000 Support Post-Quantum Cryptography (ML-DSA) OIDC token signing and key… by arnabnandy7 · Pull Request #50358 · 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
16 changes: 16 additions & 0 deletions core/src/main/java/org/keycloak/TokenVerifier.java
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
import javax.crypto.SecretKey;

import org.keycloak.common.VerificationException;
import org.keycloak.crypto.AsymmetricSignatureVerifierContext;
import org.keycloak.crypto.KeyType;
import org.keycloak.crypto.KeyWrapper;
import org.keycloak.crypto.SignatureVerifierContext;
import org.keycloak.exceptions.TokenNotActiveException;
import org.keycloak.exceptions.TokenSignatureInvalidException;
Expand Down Expand Up @@ -461,6 +464,19 @@ public void verifySignature() throws VerificationException {
throw new TokenSignatureInvalidException(token, "Invalid token signature");
}
break;
case MLDSA:
if (publicKey == null) {
throw new VerificationException("Public key not set");
}
KeyWrapper key = new KeyWrapper();
key.setType(KeyType.AKP);
key.setAlgorithm(jws.getHeader().getRawAlgorithm());
key.setPublicKey(publicKey);
if (!new AsymmetricSignatureVerifierContext(key).verify(
jws.getEncodedSignatureInput().getBytes(StandardCharsets.UTF_8), jws.getSignature())) {
throw new TokenSignatureInvalidException(token, "Invalid token signature");
}
break;
case HMAC:
if (secretKey == null) {
throw new VerificationException("Secret key not set");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,16 @@
*/
package org.keycloak.crypto;

import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.cert.X509Certificate;
import java.util.Collections;
import java.util.List;

import org.keycloak.common.crypto.CryptoIntegration;

public class AsymmetricSignatureSignerContext implements SignatureSignerContext {

protected final KeyWrapper key;
Expand All @@ -48,7 +52,7 @@ public String getHashAlgorithm() {
@Override
public byte[] sign(byte[] data) throws SignatureException {
try {
Signature signature = Signature.getInstance(JavaAlgorithm.getJavaAlgorithm(key.getAlgorithmOrDefault(), key.getCurve()));
Signature signature = getSignature();
signature.initSign((PrivateKey) key.getPrivateKey());
signature.update(data);
return signature.sign();
Expand All @@ -57,6 +61,22 @@ public byte[] sign(byte[] data) throws SignatureException {
}
}

private Signature getSignature()
throws NoSuchAlgorithmException, NoSuchProviderException {
if (KeyType.AKP.equals(key.getType())) {
// AKP private key encodings are not necessarily portable across providers. Use the same
// crypto provider that created and loaded the key to avoid provider-ordering mismatches.
return CryptoIntegration.getProvider().getSignature(key.getAlgorithmOrDefault());
Comment thread
arnabnandy7 marked this conversation as resolved.
Resolved
}

try {
return Signature.getInstance(JavaAlgorithm.getJavaAlgorithm(key.getAlgorithmOrDefault(), key.getCurve()));
} catch (NoSuchAlgorithmException e) {
// Retry using the current crypto provider's override implementation
return CryptoIntegration.getProvider().getSignature(key.getAlgorithmOrDefault());
}
}

@Override
public List<X509Certificate> getCertificateChain() {
if (key.getCertificateChain() != null && !key.getCertificateChain().isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,16 @@ public boolean verify(byte[] data, byte[] signature) throws VerificationExceptio
verifier.update(data);
return verifier.verify(signature);
} catch (Exception e) {
throw new VerificationException("Signing failed", e);
throw new VerificationException("Verification failed", e);
}
}

private Signature getSignature()
throws NoSuchAlgorithmException, NoSuchProviderException {
if (KeyType.AKP.equals(key.getType())) {
return CryptoIntegration.getProvider().getSignature(key.getAlgorithmOrDefault());
}

try {
return Signature.getInstance(JavaAlgorithm.getJavaAlgorithm(key.getAlgorithmOrDefault(), key.getCurve()));
} catch (NoSuchAlgorithmException e) {
Expand Down
14 changes: 14 additions & 0 deletions core/src/main/java/org/keycloak/crypto/JavaAlgorithm.java
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ public static String getJavaAlgorithm(String algorithm, String curve) {
return curve;
}
return Ed25519;
case Algorithm.ML_DSA_44:
return "ML-DSA-44";
case Algorithm.ML_DSA_65:
return "ML-DSA-65";
case Algorithm.ML_DSA_87:
return "ML-DSA-87";
case Algorithm.AES:
return AES;
default:
Expand Down Expand Up @@ -124,6 +130,10 @@ public static String getJavaAlgorithmForHash(String algorithm, String curve) {
}
}
return SHA512;
case Algorithm.ML_DSA_44:
case Algorithm.ML_DSA_65:
case Algorithm.ML_DSA_87:
return SHAKE256;
case Algorithm.AES:
return AES;
default:
Expand All @@ -142,6 +152,10 @@ public static String getKeyType(String keyAlgorithm) {
case Algorithm.Ed448:
case Algorithm.Ed25519:
return KeyType.OKP;
case Algorithm.ML_DSA_44:
case Algorithm.ML_DSA_65:
case Algorithm.ML_DSA_87:
return KeyType.AKP;
default:
return KeyType.OCT;
}
Expand Down
33 changes: 30 additions & 3 deletions core/src/main/java/org/keycloak/jose/jws/Algorithm.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
import org.keycloak.jose.jws.crypto.RSAProvider;
import org.keycloak.jose.jws.crypto.SignatureProvider;

import com.fasterxml.jackson.annotation.JsonProperty;

/**
* @author <a href="mailto:bill@burkecentral.com">Bill Burke</a>
* @version $Revision: 1 $
Expand All @@ -42,15 +44,27 @@ public enum Algorithm {
ES512(AlgorithmType.ECDSA, null),
EdDSA(AlgorithmType.EDDSA, null),
Ed25519(AlgorithmType.EDDSA, null),
Ed448(AlgorithmType.EDDSA, null)
Ed448(AlgorithmType.EDDSA, null),
@JsonProperty("ML-DSA-44")
ML_DSA_44(AlgorithmType.MLDSA, null, "ML-DSA-44"),
Comment thread
arnabnandy7 marked this conversation as resolved.
Resolved
@JsonProperty("ML-DSA-65")
ML_DSA_65(AlgorithmType.MLDSA, null, "ML-DSA-65"),
@JsonProperty("ML-DSA-87")
ML_DSA_87(AlgorithmType.MLDSA, null, "ML-DSA-87")
;

private AlgorithmType type;
private SignatureProvider provider;
private final AlgorithmType type;
private final SignatureProvider provider;
private final String name;

Algorithm(AlgorithmType type, SignatureProvider provider) {
this(type, provider, null);
}

Algorithm(AlgorithmType type, SignatureProvider provider, String name) {
this.type = type;
this.provider = provider;
this.name = name;
}

public AlgorithmType getType() {
Expand All @@ -60,4 +74,17 @@ public AlgorithmType getType() {
public SignatureProvider getProvider() {
return provider;
}

public String getName() {
return name != null ? name : name();
}

public static Algorithm fromName(String name) {
for (Algorithm algorithm : values()) {
if (algorithm.getName().equals(name)) {
return algorithm;
}
}
throw new IllegalArgumentException("No enum constant " + Algorithm.class.getCanonicalName() + "." + name);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public enum AlgorithmType {
HMAC,
AES,
ECDSA,
EDDSA
EDDSA,
MLDSA
Comment thread
arnabnandy7 marked this conversation as resolved.
Resolved

}
2 changes: 1 addition & 1 deletion core/src/main/java/org/keycloak/jose/jws/JWSBuilder.java
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ protected String encodeAll(StringBuilder encoding, byte[] signature) {
}

protected void encode(Algorithm alg, byte[] data, StringBuilder encoding) {
encode(alg.name(), data, encoding);
encode(alg.getName(), data, encoding);
}

protected void encode(String sigAlgName, byte[] data, StringBuilder encoding) {
Expand Down
2 changes: 1 addition & 1 deletion core/src/main/java/org/keycloak/jose/jws/JWSHeader.java
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public void setAlgorithm(Algorithm algorithm) {
@JsonIgnore
@Override
public String getRawAlgorithm() {
return getAlgorithm().name();
return getAlgorithm().getName();
}

public String getType() {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public static String getJavaAlgorithm(Algorithm alg) {
}

public static boolean verify(JWSInput jws, PublicKey publicKey) {
String alg = jws.getHeader().getAlgorithm().name();
String alg = jws.getHeader().getRawAlgorithm();
try {
KeyWrapper kw = new KeyWrapper();
kw.setPublicKey(publicKey);
Expand Down
8 changes: 7 additions & 1 deletion core/src/main/java/org/keycloak/util/JWKSUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
import org.keycloak.crypto.KeyUse;
import org.keycloak.crypto.KeyWrapper;
import org.keycloak.crypto.PublicKeysWrapper;
import org.keycloak.jose.jwk.AKPPublicJWK;
import org.keycloak.jose.jwk.ECPublicJWK;
import org.keycloak.jose.jwk.JSONWebKeySet;
import org.keycloak.jose.jwk.JWK;
Expand All @@ -56,6 +57,7 @@ public class JWKSUtils {
JWK_THUMBPRINT_REQUIRED_MEMBERS.put(KeyType.RSA, new String[] { RSAPublicJWK.MODULUS, RSAPublicJWK.PUBLIC_EXPONENT });
JWK_THUMBPRINT_REQUIRED_MEMBERS.put(KeyType.EC, new String[] { ECPublicJWK.CRV, ECPublicJWK.X, ECPublicJWK.Y });
JWK_THUMBPRINT_REQUIRED_MEMBERS.put(KeyType.OKP, new String[] { OKPPublicJWK.CRV, OKPPublicJWK.X });
JWK_THUMBPRINT_REQUIRED_MEMBERS.put(KeyType.AKP, new String[] { JWK.ALGORITHM, AKPPublicJWK.PUB });
}

/**
Expand Down Expand Up @@ -168,7 +170,11 @@ public static String computeThumbprint(JWK key, String hashAlg) {

try {
for (String member : requiredMembers) {
members.put(member, key.getOtherClaim(member, String.class));
if (JWK.ALGORITHM.equals(member)) {
members.put(member, key.getAlgorithm());
} else {
members.put(member, key.getOtherClaim(member, String.class));
Comment thread
arnabnandy7 marked this conversation as resolved.
Resolved
}
}

byte[] bytes = KeycloakJsonMapperFactory.mapper().writeValueAsBytes(members);
Expand Down
2 changes: 2 additions & 0 deletions core/src/main/java/org/keycloak/util/KeyWrapperUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public static SignatureSignerContext createSignatureSignerContext(KeyWrapper key
return new ECDSASignatureSignerContext(keyWrapper);
case KeyType.RSA:
case KeyType.OKP:
case KeyType.AKP:
return new AsymmetricSignatureSignerContext(keyWrapper);
default:
throw new IllegalArgumentException("No signer provider for key algorithm type " + keyWrapper.getType());
Expand All @@ -29,6 +30,7 @@ public static SignatureVerifierContext createSignatureVerifierContext(KeyWrapper
return new ECDSASignatureVerifierContext(keyWrapper);
case KeyType.RSA:
case KeyType.OKP:
case KeyType.AKP:
return new AsymmetricSignatureVerifierContext(keyWrapper);
default:
throw new IllegalArgumentException("No signer provider for key algorithm type " + keyWrapper.getType());
Expand Down
13 changes: 13 additions & 0 deletions core/src/test/java/org/keycloak/util/JWKSUtilsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import org.keycloak.crypto.KeyUse;
import org.keycloak.crypto.KeyWrapper;
import org.keycloak.crypto.PublicKeysWrapper;
import org.keycloak.jose.jwk.AKPSamples;
import org.keycloak.jose.jwk.ECPublicJWK;
import org.keycloak.jose.jwk.JSONWebKeySet;
import org.keycloak.jose.jwk.JWK;
Expand Down Expand Up @@ -67,6 +68,18 @@ public void unsupportedKeyType() throws Exception {
assertThrows(UnsupportedOperationException.class, () -> JWKSUtils.computeThumbprint(publicKey));
}

@Test
public void publicAkpThumbprints() throws Exception {
assertAkpThumbprint(AKPSamples.ML_DSA_44, "T4xl70S7MT6Zeq6r9V9fPJGVn76wfnXJ21-gyo0Gu6o");
assertAkpThumbprint(AKPSamples.ML_DSA_65, "Suiu29qbfuaBaR4Ats-c6XQBePB_OpAxAwcTR_0KXVM");
assertAkpThumbprint(AKPSamples.ML_DSA_87, "tRn1JNIkgMsABVQBlXeDHxAIcclh-2IX0UdDEzPt5XU");
}

private static void assertAkpThumbprint(String json, String expectedThumbprint) throws Exception {
JWK publicKey = JsonSerialization.readValue(json, JWK.class);
assertEquals(expectedThumbprint, JWKSUtils.computeThumbprint(publicKey));
}

@Test
public void publicRs256() throws Exception {

Expand Down
2 changes: 1 addition & 1 deletion js/apps/admin-ui/src/realm-settings/TokensTab.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export const RealmSettingsTokensTab = ({

const defaultSigAlgOptions = sortProviders(
serverInfo.providers!["signature"].providers,
);
).filter((algorithm) => !algorithm.startsWith("ML-DSA-"));

const asymmetricSigAlgOptions =
serverInfo.cryptoInfo?.clientSignatureAsymmetricAlgorithms ?? [];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public interface SignatureProviderFactory extends ProviderFactory<SignatureProvi
Set<String> RSA_PRIVATE_JWK_CLAIMS = Set.of("d", "p", "q", "dp", "dq", "qi", "oth");
Set<String> EC_PRIVATE_JWK_CLAIMS = Set.of("d");
Set<String> OKP_PRIVATE_JWK_CLAIMS = Set.of("d");
Set<String> AKP_PRIVATE_JWK_CLAIMS = Set.of("priv");
Set<String> OCT_PRIVATE_JWK_CLAIMS = Set.of("k");

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ public boolean isOIDCCIBAGrantEnabled(ClientModel client) {

public Algorithm getBackchannelAuthRequestSigningAlg(ClientModel client) {
String alg = client.getAttribute(CIBA_BACKCHANNEL_AUTH_REQUEST_SIGNING_ALG);
return alg==null ? null : Enum.valueOf(Algorithm.class, alg);
return alg == null ? null : Algorithm.fromName(alg);
}

public String getBackchannelClientNotificationEndpoint(ClientModel client) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ public boolean validateSignatureAlgorithm(String expectedSignatureAlg) {
return failure("Invalid signature algorithm");
}

String algorithmName = jws.getHeader().getAlgorithm().name();
String algorithmName = jws.getHeader().getRawAlgorithm();

if ("none".equalsIgnoreCase(algorithmName)) {
return failure("Invalid signature algorithm");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -404,7 +404,7 @@ private void validateClientAttestationJwt(ClientAuthenticationFlowContext contex
// Client Attestation JWT signature check
//
Algorithm algorithm = jws.getHeader().getAlgorithm();
SignatureProvider signatureProvider = session.getProvider(SignatureProvider.class, algorithm.name());
SignatureProvider signatureProvider = session.getProvider(SignatureProvider.class, algorithm.getName());
if (signatureProvider == null) {
throw new TokenVerificationException(attestationJwt, "Signature provider not found for algorithm: " + algorithm);
}
Expand Down Expand Up @@ -481,7 +481,7 @@ private void validateClientAttestationPoPJwt(ClientAuthenticationFlowContext con
// Client Attestation PoP JWT signature check
//
Algorithm algorithm = jws.getHeader().getAlgorithm();
SignatureProvider signatureProvider = session.getProvider(SignatureProvider.class, algorithm.name());
SignatureProvider signatureProvider = session.getProvider(SignatureProvider.class, algorithm.getName());
if (signatureProvider == null) {
throw new TokenVerificationException(attestationPoPJwt, "Signature provider not found for algorithm: " + algorithm);
}
Expand Down
Loading
Loading
0