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 @@ -25,6 +25,7 @@
import org.keycloak.authentication.AuthenticationFlowContext;
import org.keycloak.authentication.authenticators.broker.util.ExistingUserInfo;
import org.keycloak.authentication.authenticators.broker.util.SerializedBrokeredIdentityContext;
import org.keycloak.authentication.authenticators.util.AuthenticatorUtils;
import org.keycloak.broker.provider.BrokeredIdentityContext;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
Expand Down Expand Up @@ -73,6 +74,13 @@ protected void authenticateImpl(AuthenticationFlowContext context, SerializedBro
return;
}

if (AuthenticatorUtils.isUsernameTooLong(username)) {
ServicesLogger.LOGGER.resetFlow("Username exceeds maximum length");
context.getAuthenticationSession().setAuthNote(ENFORCE_UPDATE_PROFILE, "true");
context.resetFlow();
return;
}

IdentityProviderModel broker = brokerContext.getIdpConfig();
ExistingUserInfo duplication = broker.isTransientUsers() ? null : checkExistingUser(context, username, serializedCtx, brokerContext);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,13 @@ private UserModel getUserFromForm(AuthenticationFlowContext context, Multivalued
// remove leading and trailing whitespace
username = username.trim();

if (AuthenticatorUtils.isUsernameTooLong(username)) {
context.getEvent().error(Errors.USER_NOT_FOUND);
Response challengeResponse = challenge(context, getDefaultChallengeMessage(context), FIELD_USERNAME);
context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
return null;
}

context.getEvent().detail(Details.USERNAME, username);
context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,28 @@ public class ValidateUsername extends AbstractDirectGrantAuthenticator {
@Override
public void authenticate(AuthenticationFlowContext context) {
String username = retrieveUsername(context);
if (username == null) {

if (username != null) {
username = username.trim();
}

if (username == null || username.isEmpty()) {
context.getEvent().error(Errors.USER_NOT_FOUND);
Response challengeResponse = errorResponse(Response.Status.UNAUTHORIZED.getStatusCode(), "invalid_request", "Missing parameter: username");
context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
return;
}

if (AuthenticatorUtils.isUsernameTooLong(username)) {
context.getEvent().error(Errors.USER_NOT_FOUND);
Response challengeResponse = errorResponse(
Response.Status.BAD_REQUEST.getStatusCode(),
"invalid_grant",
"Invalid user credentials");
context.failure(AuthenticationFlowError.INVALID_USER, challengeResponse);
return;
}

context.getEvent().detail(Details.USERNAME, username);
Comment thread
msdaly200 marked this conversation as resolved.
context.getAuthenticationSession().setAuthNote(AbstractUsernameFormAuthenticator.ATTEMPTED_USERNAME, username);

Expand Down Expand Up @@ -175,7 +191,7 @@ public List<ProviderConfigProperty> getConfigProperties() {
public String getId() {
return PROVIDER_ID;
}

protected String retrieveUsername(AuthenticationFlowContext context) {
MultivaluedMap<String, String> inputData = context.getHttpRequest().getDecodedFormParameters();
return inputData.getFirst(AuthenticationManager.FORM_USERNAME);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import org.keycloak.authentication.AuthenticatorFactory;
import org.keycloak.authentication.authenticators.broker.AbstractIdpAuthenticator;
import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;
import org.keycloak.authentication.authenticators.util.AuthenticatorUtils;
import org.keycloak.events.Details;
import org.keycloak.events.Errors;
import org.keycloak.events.EventBuilder;
Expand Down Expand Up @@ -110,6 +111,14 @@ public void action(AuthenticationFlowContext context) {
}

username = username.trim();
if (AuthenticatorUtils.isUsernameTooLong(username)) {
event.error(Errors.USER_NOT_FOUND);
Response challengeResponse = context.form()
.addError(new FormMessage(Validation.FIELD_USERNAME, Messages.INVALID_USER))
.createPasswordReset();
context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
return;
}

RealmModel realm = context.getRealm();
UserModel user = context.getSession().users().getUserByUsername(realm, username);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
import org.keycloak.models.UserModel;
import org.keycloak.models.UserSessionModel;
import org.keycloak.services.managers.BruteForceProtector;
import org.keycloak.services.validation.Validation;
import org.keycloak.sessions.AuthenticationSessionModel;
import org.keycloak.util.JsonSerialization;

Expand Down Expand Up @@ -84,6 +85,18 @@ public static void dummyHash(AuthenticationFlowContext context) {
provider.encodedCredential("SlightlyLongerDummyPassword", iterations);
}

/**
* Returns {@code true} if {@code username} exceeds the maximum length allowed by the
* USER_ENTITY table column (VARCHAR(255)). Callers should invoke {@link #dummyHash(AuthenticationFlowContext)}
* and return their appropriate failure response when this returns {@code true}.
*
* @param username the trimmed username string to test; may be {@code null}
* @return true if the username is too long to be stored
*/
public static boolean isUsernameTooLong(String username) {
return username != null && username.length() > Validation.MAX_USERNAME_LENGTH;
}

/**
* Get all completed authenticator executions from the user session notes.
* @param note The serialized note value to parse
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import org.keycloak.authentication.authenticators.browser.WebAuthnConditionalUIAuthenticator;
import org.keycloak.authentication.authenticators.util.AuthenticatorUtils;
import org.keycloak.email.freemarker.beans.ProfileBean;
import org.keycloak.events.Errors;
import org.keycloak.forms.login.LoginFormsProvider;
import org.keycloak.forms.login.freemarker.model.AuthenticationContextBean;
import org.keycloak.forms.login.freemarker.model.IdentityProviderBean;
Expand Down Expand Up @@ -132,6 +133,10 @@ public void action(AuthenticationFlowContext context) {

UserModel user = context.getUser();

if (username != null) {
username = username.trim();
}

if (user == null && isBlank(username)) {
initialChallenge(context, form -> {
form.addError(new FormMessage(UserModel.USERNAME, Messages.INVALID_USERNAME));
Expand All @@ -140,6 +145,15 @@ public void action(AuthenticationFlowContext context) {
return;
}

if (AuthenticatorUtils.isUsernameTooLong(username)) {
context.getEvent().error(Errors.USER_NOT_FOUND);
Response challengeResponse = context.form()
.addError(new FormMessage(UserModel.USERNAME, Messages.INVALID_USERNAME))
.createLoginUsername();
context.failureChallenge(AuthenticationFlowError.INVALID_USER, challengeResponse);
return;
}

action(context, username);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class Validation {
public static final String FIELD_USERNAME = "username";
public static final String FIELD_OTP_CODE = "totp";
public static final String FIELD_OTP_LABEL = "userLabel";
public static final int MAX_USERNAME_LENGTH = 255; // USER_ENTITY table

private static final Pattern USERNAME_PATTERN = Pattern.compile("^[\\p{IsLatin}|\\p{IsCommon}]+$");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,14 @@
import org.keycloak.utils.StringUtil;
import org.keycloak.validate.ValidatorConfig;
import org.keycloak.validate.validators.EmailValidator;
import org.keycloak.validate.validators.LengthValidator;

import org.jspecify.annotations.NonNull;

import static java.util.Optional.ofNullable;

import static org.keycloak.common.util.ObjectUtil.isBlank;
import static org.keycloak.services.validation.Validation.MAX_USERNAME_LENGTH;
import static org.keycloak.userprofile.DefaultAttributes.READ_ONLY_ATTRIBUTE_KEY;
import static org.keycloak.userprofile.UserProfileContext.ACCOUNT;
import static org.keycloak.userprofile.UserProfileContext.IDP_REVIEW;
Expand Down Expand Up @@ -424,7 +426,9 @@ private UserProfileMetadata createBrokeringProfile(AttributeValidatorMetadata re
UserProfileMetadata metadata = new UserProfileMetadata(IDP_REVIEW);

metadata.addAttribute(UserModel.USERNAME, -2, DeclarativeUserProfileProviderFactory::editUsernameCondition,
DeclarativeUserProfileProviderFactory::readUsernameCondition, new AttributeValidatorMetadata(BrokeringFederatedUsernameHasValueValidator.ID)).setAttributeDisplayName("${username}");
DeclarativeUserProfileProviderFactory::readUsernameCondition,
new AttributeValidatorMetadata(BrokeringFederatedUsernameHasValueValidator.ID),
createUsernameLengthValidator()).setAttributeDisplayName("${username}");

metadata.addAttribute(UserModel.EMAIL, -1,
new AttributeValidatorMetadata(BlankAttributeValidator.ID, BlankAttributeValidator.createConfig(Messages.MISSING_EMAIL, true)))
Expand Down Expand Up @@ -466,7 +470,8 @@ private UserProfileMetadata createDefaultProfile(UserProfileContext context, Att
DeclarativeUserProfileProviderFactory::readUsernameCondition,
new AttributeValidatorMetadata(UsernameHasValueValidator.ID),
new AttributeValidatorMetadata(DuplicateUsernameValidator.ID),
new AttributeValidatorMetadata(UsernameMutationValidator.ID)).setAttributeDisplayName("${username}");
new AttributeValidatorMetadata(UsernameMutationValidator.ID),
createUsernameLengthValidator()).setAttributeDisplayName("${username}");

metadata.addAttribute(UserModel.EMAIL, -1,
DeclarativeUserProfileProviderFactory::editEmailCondition,
Expand Down Expand Up @@ -498,7 +503,8 @@ private UserProfileMetadata createUserResourceValidation(Config.Scope config) {

metadata.addAttribute(UserModel.USERNAME, -2,
new AttributeValidatorMetadata(UsernameHasValueValidator.ID),
new AttributeValidatorMetadata(DuplicateUsernameValidator.ID))
new AttributeValidatorMetadata(DuplicateUsernameValidator.ID),
createUsernameLengthValidator())
.addWriteCondition(DeclarativeUserProfileProviderFactory::editUsernameCondition);
metadata.addAttribute(UserModel.EMAIL, -1,
new AttributeValidatorMetadata(DuplicateEmailValidator.ID),
Expand Down Expand Up @@ -612,4 +618,13 @@ private boolean isUpdateEmailFeatureEnabled(AttributeContext context) {

return UpdateEmail.isEnabled(realm);
}

private AttributeValidatorMetadata createUsernameLengthValidator() {
// IDP_REVIEW (brokering) profile has no UsernameHasValueValidator, provides the lower-bound guard.
return new AttributeValidatorMetadata(LengthValidator.ID,
ValidatorConfig.builder()
.config(LengthValidator.KEY_MIN, "1")
.config(LengthValidator.KEY_MAX, String.valueOf(MAX_USERNAME_LENGTH))
.build());
Comment thread
msdaly200 marked this conversation as resolved.
}
}
Loading
Loading