8000 Fix client secret length to always use HS512 entropy #49793 by MdTanwer · Pull Request #50083 · keycloak/keycloak · GitHub
[go: up one dir, main page]

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
8000
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,6 @@
import org.keycloak.common.util.Time;
import org.keycloak.component.ComponentModel;
import org.keycloak.constants.OID4VCIConstants;
import org.keycloak.crypto.Algorithm;
import org.keycloak.deployment.DeployedConfigurationsManager;
import org.keycloak.models.AccountRoles;
import org.keycloak.models.AuthenticationExecutionModel;
Expand All @@ -85,7 +84,6 @@
import org.keycloak.models.ScopeContainerModel;
import org.keycloak.models.UserModel;
import org.keycloak.organization.OrganizationProvider;
import org.keycloak.protocol.oidc.OIDCConfigAttributes;
import org.keycloak.provider.Provider;
import org.keycloak.provider.ProviderFactory;
import org.keycloak.representations.idm.CertificateRepresentation;
Expand Down Expand Up @@ -253,13 +251,21 @@ public static CertificateRepresentation generateKeyPairCertificate(String subjec
}

public static String generateSecret(ClientModel client) {
int secretLength = getSecretLengthByAuthenticationType(client.getClientAuthenticatorType(), client.getAttribute(OIDCConfigAttributes.TOKEN_ENDPOINT_AUTH_SIGNING_ALG));
int secretLength = getRequiredClientSecretLength();
String secret = SecretGenerator.getInstance().randomString(secretLength);
client.setSecret(secret);
client.setAttribute(ClientSecretConstants.CLIENT_SECRET_CREATION_TIME, String.valueOf(Time.currentTime()));
return secret;
}

/**
* Returns the required length for a client secret in alphanumeric characters.
* Always generated at HS512-level entropy to cover all HMAC signature use cases.
*/
public static int getRequiredClientSecretLength() {
return SecretGenerator.equivalentEntropySize(SecretGenerator.SECRET_LENGTH_512_BITS, SecretGenerator.ALPHANUM.length);
}

public static String getDefaultClientAuthenticatorType() {
return AUTH_TYPE_CLIENT_SECRET;
}
Expand Down Expand Up @@ -1305,22 +1311,12 @@ public static String getIdentityProviderDisplayName(KeycloakSession session, Ide
}

/**
* @param clientAuthenticatorType
* @return secret size based on authentication type
* @param clientAuthenticatorType ignored, kept for backwards compatibility
* @param signingAlg ignored, kept for backwards compatibility
* @return secret size in alphanumeric characters with HS512-level entropy
*/
public static int getSecretLengthByAuthenticationType(String clientAuthenticatorType, String signingAlg) {
if (clientAuthenticatorType != null)
switch (clientAuthenticatorType) {
case AUTH_TYPE_CLIENT_SECRET_JWT: {
if (Algorithm.HS384.equals(signingAlg))
return SecretGenerator.equivalentEntropySize(SecretGenerator.SECRET_LENGTH_384_BITS, SecretGenerator.ALPHANUM.length);
else if (Algorithm.HS512.equals(signingAlg))
return SecretGenerator.equivalentEntropySize(SecretGenerator.SECRET_LENGTH_512_BITS, SecretGenerator.ALPHANUM.length);
else
return SecretGenerator.equivalentEntropySize(SecretGenerator.SECRET_LENGTH_256_BITS, SecretGenerator.ALPHANUM.length);
}
}
return SecretGenerator.SECRET_LENGTH_256_BITS;
return getRequiredClientSecretLength();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@
import java.util.Base64;
import java.util.UUID;

import org.keycloak.common.util.SecretGenerator;
import org.keycloak.crypto.Algorithm;

import org.junit.Assert;
import org.junit.Test;

Expand All @@ -39,6 +42,21 @@ public void testGenerateId() {
Assert.assertEquals(id, uuid.toString());
}

@Test
public void testGetRequiredClientSecretLength() {
Assert.assertEquals(
SecretGenerator.equivalentEntropySize(SecretGenerator.SECRET_LENGTH_512_BITS, SecretGenerator.ALPHANUM.length),
KeycloakModelUtils.getRequiredClientSecretLength());
}

@Test
public void testGetSecretLengthByAuthenticationTypeAlwaysUsesHs512Entropy() {
int requiredLength = KeycloakModelUtils.getRequiredClientSecretLength();
Assert.assertEquals(requiredLength, KeycloakModelUtils.getSecretLengthByAuthenticationType("client-secret", null));
Assert.assertEquals(requiredLength, KeycloakModelUtils.getSecretLengthByAuthenticationType("client-secret-jwt", Algorithm.HS256));
Assert.assertEquals(requiredLength, KeycloakModelUtils.getSecretLengthByAuthenticationType("client-secret-jwt", Algorithm.HS512));
}

@Test
public void testGenerateShortId() {
final String shortId = KeycloakModelUtils.generateShortId();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -280,31 +280,61 @@ private void testCodeToTokenRequestSuccess(String algorithm) throws Exception {
*/
@Test
public void authenticateWithValidClientSecretWhenRotationPolicyIsEnableForHS256() throws Exception {
processAuthenticateWithAlgorithm(Algorithm.HS256, SecretGenerator.SECRET_LENGTH_256_BITS);
processAuthenticateWithAlgorithm(Algorithm.HS256);
}

@Test
public void authenticateWithValidClientSecretWhenRotationPolicyIsEnableForHS384() throws Exception {
processAuthenticateWithAlgorithm(Algorithm.HS384, SecretGenerator.SECRET_LENGTH_384_BITS);
processAuthenticateWithAlgorithm(Algorithm.HS384);
}

@Test
public void authenticateWithValidClientSecretWhenRotationPolicyIsEnableForHS512() throws Exception {
processAuthenticateWithAlgorithm(Algorithm.HS512, SecretGenerator.SECRET_LENGTH_512_BITS);
processAuthenticateWithAlgorithm(Algorithm.HS512);
}

private void processAuthenticateWithAlgorithm(String algorithm, Integer secretLength) throws Exception{
@Test
public void regenerateClientSecretForClientSecretBasicWithIdTokenHs512() throws Exception {
ClientRepresentation clientRep = new ClientRepresentation();
clientRep.setClientId("basic-hs512-client");
clientRep.setName("basic-hs512-client");
clientRep.setProtocol(OIDC);
clientRep.setBearerOnly(Boolean.FALSE);
clientRep.setPublicClient(Boolean.FALSE);
clientRep.setClientAuthenticatorType("client-secret");
clientRep.setStandardFlowEnabled(Boolean.TRUE);
clientRep.setAttributes(new HashMap<>());
clientRep.getAttributes().put(OIDCConfigAttributes.ID_TOKEN_SIGNED_RESPONSE_ALG, Algorithm.HS512);
clientRep.setRedirectUris(Collections.singletonList(
ServerURLs.getAuthServerContextRoot() + "/auth/realms/master/app/auth"));

Response resp = adminClient.realm(REALM_NAME).clients().create(clientRep);
assertEquals(Response.Status.CREATED.getStatusCode(), resp.getStatus());
String clientUuid = ApiUtil.getCreatedId(resp);
resp.close();
testContext.getOrCreateCleanup(REALM_NAME).addClientUuid(clientUuid);

ClientResource clientResource = adminClient.realm(REALM_NAME).clients().get(clientUuid);
String secret = clientResource.generateNewSecret().getValue();
assertThat(secret.length(), is(SecretGenerator.equivalentEntropySize(
SecretGenerator.SECRET_LENGTH_512_BITS, SecretGenerator.ALPHANUM.length)));
}

private void processAuthenticateWithAlgorithm(String algorithm) throws Exception{
String cidConfidential= createClientByAdmin("jwt-client","jwt-client",CLIENT_SECRET,algorithm);
ClientResource clientResource = adminClient.realm(REALM_NAME).clients().get(cidConfidential);
configureDefaultProfileAndPolicy();

int requiredSecretLength = SecretGenerator.equivalentEntropySize(
SecretGenerator.SECRET_LENGTH_512_BITS, SecretGenerator.ALPHANUM.length);

String firstSecret = clientResource.generateNewSecret().getValue(); //clientResource.getSecret().getValue();
assertThat(firstSecret.length(), is(SecretGenerator.equivalentEntropySize(secretLength, SecretGenerator.ALPHANUM.length)));
assertThat(firstSecret.length(), is(requiredSecretLength));

//generate new secret, rotate the secret
String newSecret = clientResource.generateNewSecret().getValue();
assertThat(firstSecret, not(equalTo(newSecret)));
assertThat(newSecret.length(), is(SecretGenerator.equivalentEntropySize(secretLength, SecretGenerator.ALPHANUM.length)));
assertThat(newSecret.length(), is(requiredSecretLength));

oauth.client("jwt-client");
oauth.doLogin("test-user@localhost", "password");
Expand Down
Loading
0