KEYCLOAK-19699 RSA key provider with key use = enc cannot select corresponding algorithm on Admin Console

This commit is contained in:
Takashi Norimatsu 2021-11-04 12:07:31 +09:00 committed by Marek Posolda
parent ed6eea26ea
commit 10c3e149d3
7 changed files with 323 additions and 108 deletions

View file

@ -21,6 +21,7 @@ import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.component.ComponentModel;
import org.keycloak.crypto.Algorithm;
import org.keycloak.crypto.KeyUse;
import org.keycloak.jose.jwe.JWEConstants;
import org.keycloak.keys.KeyProvider;
import org.keycloak.models.RealmModel;
@ -33,15 +34,18 @@ public class DefaultKeyProviders {
public static void createProviders(RealmModel realm) {
if (!hasProvider(realm, "rsa-generated")) {
createRsaKeyProvider("rsa-generated", KeyUse.SIG, realm);
createRsaKeyProvider("rsa-enc-generated", KeyUse.ENC, realm);
createRsaKeyProvider("rsa-generated", realm);
}
if (!hasProvider(realm, "rsa-enc-generated")) {
createRsaEncKeyProvider("rsa-enc-generated", realm);
}
createSecretProvider(realm);
createAesProvider(realm);
}
private static void createRsaKeyProvider(String name, KeyUse keyUse, RealmModel realm) {
private static void createRsaKeyProvider(String name, RealmModel realm) {
ComponentModel generated = new ComponentModel();
generated.setName(name);
generated.setParentId(realm.getId());
@ -50,7 +54,23 @@ public class DefaultKeyProviders {
MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
config.putSingle("priority", "100");
config.putSingle("keyUse", keyUse.getSpecName());
config.putSingle("keyUse", KeyUse.SIG.name());
generated.setConfig(config);
realm.addComponentModel(generated);
}
private static void createRsaEncKeyProvider(String name, RealmModel realm) {
ComponentModel generated = new ComponentModel();
generated.setName(name);
generated.setParentId(realm.getId());
generated.setProviderId("rsa-enc-generated");
generated.setProviderType(KeyProvider.class.getName());
MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
config.putSingle("priority", "100");
config.putSingle("keyUse", KeyUse.ENC.name());
config.putSingle("algorithm", JWEConstants.RSA_OAEP);
generated.setConfig(config);
realm.addComponentModel(generated);

View file

@ -0,0 +1,120 @@
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.keys;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPrivateKey;
import org.jboss.logging.Logger;
import org.keycloak.common.util.CertificateUtils;
import org.keycloak.common.util.KeyUtils;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.common.util.PemUtils;
import org.keycloak.component.ComponentModel;
import org.keycloak.component.ComponentValidationException;
import org.keycloak.crypto.KeyUse;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.provider.ConfigurationValidationHelper;
import org.keycloak.provider.ProviderConfigurationBuilder;
public abstract class AbstractGeneratedRsaKeyProviderFactory extends AbstractRsaKeyProviderFactory {
abstract protected Logger getLogger();
public final static ProviderConfigurationBuilder rsaKeyConfigurationBuilder() {
return ProviderConfigurationBuilder.create()
.property(Attributes.PRIORITY_PROPERTY)
.property(Attributes.ENABLED_PROPERTY)
.property(Attributes.ACTIVE_PROPERTY);
}
@Override
public boolean createFallbackKeys(KeycloakSession session, KeyUse keyUse, String algorithm) {
if (isValidKeyUse(keyUse) && isSupportedRsaAlgorithm(algorithm)) {
RealmModel realm = session.getContext().getRealm();
ComponentModel generated = new ComponentModel();
generated.setName("fallback-" + algorithm);
generated.setParentId(realm.getId());
generated.setProviderId(getId());
generated.setProviderType(KeyProvider.class.getName());
MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
config.putSingle(Attributes.PRIORITY_KEY, "-100");
config.putSingle(Attributes.ALGORITHM_KEY, algorithm);
generated.setConfig(config);
realm.addComponentModel(generated);
return true;
} else {
return false;
}
}
abstract protected boolean isValidKeyUse(KeyUse keyUse);
abstract protected boolean isSupportedRsaAlgorithm(String algorithm);
@Override
public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) throws ComponentValidationException {
super.validateConfiguration(session, realm, model);
ConfigurationValidationHelper.check(model).checkList(Attributes.KEY_SIZE_PROPERTY, false);
int size = model.get(Attributes.KEY_SIZE_KEY, 2048);
if (!(model.contains(Attributes.PRIVATE_KEY_KEY) && model.contains(Attributes.CERTIFICATE_KEY))) {
generateKeys(realm, model, size);
getLogger().debugv("Generated keys for {0}", realm.getName());
} else {
PrivateKey privateKey = PemUtils.decodePrivateKey(model.get(Attributes.PRIVATE_KEY_KEY));
int currentSize = ((RSAPrivateKey) privateKey).getModulus().bitLength();
if (currentSize != size) {
generateKeys(realm, model, size);
getLogger().debugv("Key size changed, generating new keys for {0}", realm.getName());
}
}
}
private void generateKeys(RealmModel realm, ComponentModel model, int size) {
KeyPair keyPair;
try {
keyPair = KeyUtils.generateRsaKeyPair(size);
model.put(Attributes.PRIVATE_KEY_KEY, PemUtils.encodeKey(keyPair.getPrivate()));
} catch (Throwable t) {
throw new ComponentValidationException("Failed to generate keys", t);
}
generateCertificate(realm, model, keyPair);
}
private void generateCertificate(RealmModel realm, ComponentModel model, KeyPair keyPair) {
try {
Certificate certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, realm.getName());
model.put(Attributes.CERTIFICATE_KEY, PemUtils.encodeCertificate(certificate));
} catch (Throwable t) {
throw new ComponentValidationException("Failed to generate certificate", t);
}
}
}

View file

@ -19,6 +19,7 @@ package org.keycloak.keys;
import org.keycloak.crypto.Algorithm;
import org.keycloak.crypto.KeyUse;
import org.keycloak.jose.jwe.JWEConstants;
import org.keycloak.provider.ProviderConfigProperty;
import static org.keycloak.provider.ProviderConfigProperty.*;
@ -69,4 +70,8 @@ public interface Attributes {
Algorithm.HS256,
Algorithm.HS256, Algorithm.HS384, Algorithm.HS512);
ProviderConfigProperty RS_ENC_ALGORITHM_PROPERTY = new ProviderConfigProperty(ALGORITHM_KEY, "Algorithm", "Intended algorithm for the key encryption", LIST_TYPE,
JWEConstants.RSA_OAEP,
JWEConstants.RSA1_5, JWEConstants.RSA_OAEP, JWEConstants.RSA_OAEP_256);
}

View file

@ -0,0 +1,83 @@
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.keys;
import java.util.List;
import org.jboss.logging.Logger;
import org.keycloak.component.ComponentModel;
import org.keycloak.crypto.KeyUse;
import org.keycloak.jose.jwe.JWEConstants;
import org.keycloak.models.KeycloakSession;
import org.keycloak.provider.ProviderConfigProperty;
/**
* @author <a href="mailto:takashi.norimatsu.ws@hitachi.com">Takashi Norimatsu</a>
*/
public class GeneratedRsaEncKeyProviderFactory extends AbstractGeneratedRsaKeyProviderFactory {
private static final Logger logger = Logger.getLogger(GeneratedRsaEncKeyProviderFactory.class);
public static final String ID = "rsa-enc-generated";
private static final String HELP_TEXT = "Generates RSA keys for key encryption and creates a self-signed certificate";
private static final List<ProviderConfigProperty> CONFIG_PROPERTIES = AbstractGeneratedRsaKeyProviderFactory.rsaKeyConfigurationBuilder()
.property(Attributes.KEY_SIZE_PROPERTY)
.property(Attributes.RS_ENC_ALGORITHM_PROPERTY)
.build();
@Override
public KeyProvider create(KeycloakSession session, ComponentModel model) {
model.put(Attributes.KEY_USE, KeyUse.ENC.name());
return new ImportedRsaKeyProvider(session.getContext().getRealm(), model);
}
@Override
public String getHelpText() {
return HELP_TEXT;
}
@Override
public List<ProviderConfigProperty> getConfigProperties() {
return CONFIG_PROPERTIES;
}
@Override
public String getId() {
return ID;
}
@Override
protected boolean isValidKeyUse(KeyUse keyUse) {
return keyUse.equals(KeyUse.ENC);
}
@Override
protected boolean isSupportedRsaAlgorithm(String algorithm) {
return algorithm.equals(JWEConstants.RSA1_5)
|| algorithm.equals(JWEConstants.RSA_OAEP)
|| algorithm.equals(JWEConstants.RSA_OAEP_256);
}
@Override
protected Logger getLogger() {
return logger;
}
}

View file

@ -18,123 +18,39 @@
package org.keycloak.keys;
import org.jboss.logging.Logger;
import org.keycloak.common.util.CertificateUtils;
import org.keycloak.common.util.KeyUtils;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.common.util.PemUtils;
import org.keycloak.component.ComponentModel;
import org.keycloak.component.ComponentValidationException;
import org.keycloak.crypto.Algorithm;
import org.keycloak.crypto.KeyUse;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.RealmModel;
import org.keycloak.provider.ConfigurationValidationHelper;
import org.keycloak.provider.ProviderConfigProperty;
import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.util.List;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class GeneratedRsaKeyProviderFactory extends AbstractRsaKeyProviderFactory {
public class GeneratedRsaKeyProviderFactory extends AbstractGeneratedRsaKeyProviderFactory {
private static final Logger logger = Logger.getLogger(GeneratedRsaKeyProviderFactory.class);
public static final String ID = "rsa-generated";
private static final String HELP_TEXT = "Generates RSA keys and creates a self-signed certificate";
private static final String HELP_TEXT = "Generates RSA signature keys and creates a self-signed certificate";
private static final List<ProviderConfigProperty> CONFIG_PROPERTIES = AbstractRsaKeyProviderFactory.configurationBuilder()
private static final List<ProviderConfigProperty> CONFIG_PROPERTIES = AbstractGeneratedRsaKeyProviderFactory.rsaKeyConfigurationBuilder()
.property(Attributes.KEY_SIZE_PROPERTY)
.property(Attributes.KEY_USE_PROPERTY)
.property(Attributes.RS_ALGORITHM_PROPERTY)
.build();
@Override
public KeyProvider create(KeycloakSession session, ComponentModel model) {
if (model.getConfig().get(Attributes.KEY_USE) == null) {
// for backward compatibility : it allows "enc" key use for "rsa-generated" provider
model.put(Attributes.KEY_USE, KeyUse.SIG.name());
}
return new ImportedRsaKeyProvider(session.getContext().getRealm(), model);
}
@Override
public boolean createFallbackKeys(KeycloakSession session, KeyUse keyUse, String algorithm) {
if (keyUse.equals(KeyUse.SIG) && isSupportedRsaAlgorithm(algorithm)) {
RealmModel realm = session.getContext().getRealm();
ComponentModel generated = new ComponentModel();
generated.setName("fallback-" + algorithm);
generated.setParentId(realm.getId());
generated.setProviderId(ID);
generated.setProviderType(KeyProvider.class.getName());
MultivaluedHashMap<String, String> config = new MultivaluedHashMap<>();
config.putSingle(Attributes.PRIORITY_KEY, "-100");
config.putSingle(Attributes.ALGORITHM_KEY, algorithm);
generated.setConfig(config);
realm.addComponentModel(generated);
return true;
} else {
return false;
}
}
private boolean isSupportedRsaAlgorithm(String algorithm) {
return algorithm.equals(Algorithm.RS256)
|| algorithm.equals(Algorithm.PS256)
|| algorithm.equals(Algorithm.RS384)
|| algorithm.equals(Algorithm.PS384)
|| algorithm.equals(Algorithm.RS512)
|| algorithm.equals(Algorithm.PS512);
}
@Override
public void validateConfiguration(KeycloakSession session, RealmModel realm, ComponentModel model) throws ComponentValidationException {
super.validateConfiguration(session, realm, model);
ConfigurationValidationHelper.check(model).checkList(Attributes.KEY_SIZE_PROPERTY, false);
int size = model.get(Attributes.KEY_SIZE_KEY, 2048);
if (!(model.contains(Attributes.PRIVATE_KEY_KEY) && model.contains(Attributes.CERTIFICATE_KEY))) {
generateKeys(realm, model, size);
logger.debugv("Generated keys for {0}", realm.getName());
} else {
PrivateKey privateKey = PemUtils.decodePrivateKey(model.get(Attributes.PRIVATE_KEY_KEY));
int currentSize = ((RSAPrivateKey) privateKey).getModulus().bitLength();
if (currentSize != size) {
generateKeys(realm, model, size);
logger.debugv("Key size changed, generating new keys for {0}", realm.getName());
}
}
}
private void generateKeys(RealmModel realm, ComponentModel model, int size) {
KeyPair keyPair;
try {
keyPair = KeyUtils.generateRsaKeyPair(size);
model.put(Attributes.PRIVATE_KEY_KEY, PemUtils.encodeKey(keyPair.getPrivate()));
} catch (Throwable t) {
throw new ComponentValidationException("Failed to generate keys", t);
}
generateCertificate(realm, model, keyPair);
}
private void generateCertificate(RealmModel realm, ComponentModel model, KeyPair keyPair) {
try {
Certificate certificate = CertificateUtils.generateV1SelfSignedCertificate(keyPair, realm.getName());
model.put(Attributes.CERTIFICATE_KEY, PemUtils.encodeCertificate(certificate));
} catch (Throwable t) {
throw new ComponentValidationException("Failed to generate certificate", t);
}
}
@Override
public String getHelpText() {
return HELP_TEXT;
@ -150,4 +66,24 @@ public class GeneratedRsaKeyProviderFactory extends AbstractRsaKeyProviderFactor
return ID;
}
@Override
protected boolean isValidKeyUse(KeyUse keyUse) {
return keyUse.equals(KeyUse.SIG);
}
@Override
protected boolean isSupportedRsaAlgorithm(String algorithm) {
return algorithm.equals(Algorithm.RS256)
|| algorithm.equals(Algorithm.PS256)
|| algorithm.equals(Algorithm.RS384)
|| algorithm.equals(Algorithm.PS384)
|| algorithm.equals(Algorithm.RS512)
|| algorithm.equals(Algorithm.PS512);
}
@Override
protected Logger getLogger() {
return logger;
}
}

View file

@ -21,3 +21,4 @@ org.keycloak.keys.GeneratedRsaKeyProviderFactory
org.keycloak.keys.JavaKeystoreKeyProviderFactory
org.keycloak.keys.ImportedRsaKeyProviderFactory
org.keycloak.keys.GeneratedEcdsaKeyProviderFactory
org.keycloak.keys.GeneratedRsaEncKeyProviderFactory

View file

@ -22,9 +22,10 @@ import org.junit.Rule;
import org.junit.Test;
import org.keycloak.common.util.MultivaluedHashMap;
import org.keycloak.common.util.PemUtils;
import org.keycloak.crypto.KeyUse;
import org.keycloak.jose.jws.AlgorithmType;
import org.keycloak.keys.GeneratedRsaEncKeyProviderFactory;
import org.keycloak.keys.GeneratedRsaKeyProviderFactory;
import org.keycloak.keys.KeyMetadata;
import org.keycloak.keys.KeyProvider;
import org.keycloak.representations.idm.ComponentRepresentation;
import org.keycloak.representations.idm.ErrorRepresentation;
@ -64,10 +65,19 @@ public class GeneratedRsaKeyProviderTest extends AbstractKeycloakTest {
}
@Test
public void defaultKeysize() throws Exception {
public void defaultKeysizeForSig() throws Exception {
defaultKeysize(GeneratedRsaKeyProviderFactory.ID, KeyUse.SIG);
}
@Test
public void defaultKeysizeForEnc() throws Exception {
defaultKeysize(GeneratedRsaEncKeyProviderFactory.ID, KeyUse.ENC);
}
private void defaultKeysize(String providerId, KeyUse keyUse) throws Exception {
long priority = System.currentTimeMillis();
ComponentRepresentation rep = createRep("valid", GeneratedRsaKeyProviderFactory.ID);
ComponentRepresentation rep = createRep("valid", providerId);
rep.setConfig(new MultivaluedHashMap<>());
rep.getConfig().putSingle("priority", Long.toString(priority));
@ -88,13 +98,23 @@ public class GeneratedRsaKeyProviderTest extends AbstractKeycloakTest {
assertEquals(AlgorithmType.RSA.name(), key.getType());
assertEquals(priority, key.getProviderPriority());
assertEquals(2048, ((RSAPublicKey) PemUtils.decodePublicKey(keys.getKeys().get(0).getPublicKey())).getModulus().bitLength());
assertEquals(keyUse, key.getUse());
}
@Test
public void largeKeysize() throws Exception {
public void largeKeysizeForSig() throws Exception {
largeKeysize(GeneratedRsaKeyProviderFactory.ID, KeyUse.SIG);
}
@Test
public void largeKeysizeForEnc() throws Exception {
largeKeysize(GeneratedRsaEncKeyProviderFactory.ID, KeyUse.ENC);
}
private void largeKeysize(String providerId, KeyUse keyUse) throws Exception {
long priority = System.currentTimeMillis();
ComponentRepresentation rep = createRep("valid", GeneratedRsaKeyProviderFactory.ID);
ComponentRepresentation rep = createRep("valid", providerId);
rep.setConfig(new MultivaluedHashMap<>());
rep.getConfig().putSingle("priority", Long.toString(priority));
rep.getConfig().putSingle("keySize", "4096");
@ -116,13 +136,23 @@ public class GeneratedRsaKeyProviderTest extends AbstractKeycloakTest {
assertEquals(AlgorithmType.RSA.name(), key.getType());
assertEquals(priority, key.getProviderPriority());
assertEquals(4096, ((RSAPublicKey) PemUtils.decodePublicKey(keys.getKeys().get(0).getPublicKey())).getModulus().bitLength());
assertEquals(keyUse, key.getUse());
}
@Test
public void updatePriority() throws Exception {
public void updatePriorityForSig() throws Exception {
updatePriority(GeneratedRsaKeyProviderFactory.ID, KeyUse.SIG);
}
@Test
public void updatePriorityForEnc() throws Exception {
updatePriority(GeneratedRsaEncKeyProviderFactory.ID, KeyUse.ENC);
}
private void updatePriority(String providerId, KeyUse keyUse) throws Exception {
long priority = System.currentTimeMillis();
ComponentRepresentation rep = createRep("valid", GeneratedRsaKeyProviderFactory.ID);
ComponentRepresentation rep = createRep("valid", providerId);
rep.setConfig(new MultivaluedHashMap<>());
rep.getConfig().putSingle("priority", Long.toString(priority));
@ -147,13 +177,23 @@ public class GeneratedRsaKeyProviderTest extends AbstractKeycloakTest {
String publicKey2 = keys.getKeys().get(0).getPublicKey();
assertEquals(publicKey, publicKey2);
assertEquals(keyUse, keys.getKeys().get(0).getUse());
}
@Test
public void updateKeysize() throws Exception {
public void updateKeysizeForSig() throws Exception {
updateKeysize(GeneratedRsaKeyProviderFactory.ID, KeyUse.SIG);
}
@Test
public void updateKeysizeForEnc() throws Exception {
updateKeysize(GeneratedRsaEncKeyProviderFactory.ID, KeyUse.ENC);
}
private void updateKeysize(String providerId, KeyUse keyUse) throws Exception {
long priority = System.currentTimeMillis();
ComponentRepresentation rep = createRep("valid", GeneratedRsaKeyProviderFactory.ID);
ComponentRepresentation rep = createRep("valid", providerId);
rep.setConfig(new MultivaluedHashMap<>());
rep.getConfig().putSingle("priority", Long.toString(priority));
@ -177,11 +217,21 @@ public class GeneratedRsaKeyProviderTest extends AbstractKeycloakTest {
assertNotEquals(publicKey, publicKey2);
assertEquals(2048, ((RSAPublicKey) PemUtils.decodePublicKey(publicKey)).getModulus().bitLength());
assertEquals(4096, ((RSAPublicKey) PemUtils.decodePublicKey(publicKey2)).getModulus().bitLength());
assertEquals(keyUse, keys.getKeys().get(0).getUse());
}
@Test
public void invalidKeysize() throws Exception {
ComponentRepresentation rep = createRep("invalid", GeneratedRsaKeyProviderFactory.ID);
public void invalidKeysizeForSig() throws Exception {
invalidKeysize(GeneratedRsaKeyProviderFactory.ID);
}
@Test
public void invalidKeysizeForEnd() throws Exception {
invalidKeysize(GeneratedRsaEncKeyProviderFactory.ID);
}
private void invalidKeysize(String providerId) throws Exception {
ComponentRepresentation rep = createRep("invalid", providerId);
rep.getConfig().putSingle("keySize", "1234");
Response response = adminClient.realm("test").components().add(rep);